Commits

Ronny Pfannschmidt committed 2a804e2 Merge

merge from default

Comments (0)

Files changed (230)

+
+all: pypy-c
+
+pypy-c:
+	@echo "Building PyPy with JIT, it'll take about 40 minutes and 4G of RAM"
+	@sleep 3
+	rpython/bin/rpython -Ojit pypy/goal/targetpypystandalone.py
 and send us feedback!
 
     the pypy-dev team <pypy-dev@python.org>
+
+Building
+========
+
+build with::
+
+  rpython/bin/rpython -Ojit pypy/goal/targetpypystandalone.py
+
+This ends up with ``pypy-c`` binary in the main pypy directory. We suggest
+to use virtualenv with the resulting pypy-c as the interpreter, you can
+find more details about various installation schemes here:
+
+http://doc.pypy.org/en/latest/getting-started.html#installing-pypy

lib-python/2.7/json/decoder.py

         if nextchar == '}':
             if object_pairs_hook is not None:
                 result = object_pairs_hook(pairs)
-                return result, end
+                return result, end + 1
             pairs = {}
             if object_hook is not None:
                 pairs = object_hook(pairs)

lib-python/2.7/json/tests/test_decode.py

                                     object_pairs_hook=OrderedDict,
                                     object_hook=lambda x: None),
                          OrderedDict(p))
+        self.assertEqual(self.loads("{}", object_pairs_hook=list), [])
 
 
 class TestPyDecode(TestDecode, PyTest): pass

lib-python/2.7/test/test_descr.py

         list.__init__(a, sequence=[0, 1, 2])
         self.assertEqual(a, [0, 1, 2])
 
+    @unittest.skipIf(test_support.check_impl_detail(pypy=True) and
+                     sys.platform == 'win32',
+                     "XXX: https://bugs.pypy.org/issue1461")
     def test_recursive_call(self):
         # Testing recursive __call__() by setting to instance of class...
         class A(object):

lib-python/2.7/test/test_fileio.py

         self.assertRaises(ValueError, _FileIO, -10)
         self.assertRaises(OSError, _FileIO, make_bad_fd())
         if sys.platform == 'win32':
-            raise unittest.SkipTest('Set _invalid_parameter_handler for low level io')
             import msvcrt
             self.assertRaises(IOError, msvcrt.get_osfhandle, make_bad_fd())
 

lib_pypy/_pypy_interact.py

     import code
     if mainmodule is None:
         import __main__ as mainmodule
-    console = code.InteractiveConsole(mainmodule.__dict__)
+    console = code.InteractiveConsole(mainmodule.__dict__, filename='<stdin>')
     # some parts of code.py are copied here because it seems to be impossible
     # to start an interactive console without printing at least one line
     # of banner

lib_pypy/_sqlite3.py

 
                 # Actually execute the SQL statement
                 ret = _lib.sqlite3_step(self.__statement._statement)
-                if ret not in (_lib.SQLITE_DONE, _lib.SQLITE_ROW):
-                    self.__statement._reset()
-                    raise self.__connection._get_exception(ret)
 
                 if ret == _lib.SQLITE_ROW:
                     if multiple:
                         raise ProgrammingError("executemany() can only execute DML statements.")
                     self.__build_row_cast_map()
                     self.__next_row = self.__fetch_one_row()
-                elif ret == _lib.SQLITE_DONE and not multiple:
+                elif ret == _lib.SQLITE_DONE:
+                    if not multiple:
+                        self.__statement._reset()
+                else:
                     self.__statement._reset()
+                    raise self.__connection._get_exception(ret)
 
                 if self.__statement._type in ("UPDATE", "DELETE", "INSERT", "REPLACE"):
                     if self.__rowcount == -1:
         try:
             next_row = self.__next_row
         except AttributeError:
-            self.__statement._reset()
             raise StopIteration
         del self.__next_row
 
             next_row = self.row_factory(self, next_row)
 
         ret = _lib.sqlite3_step(self.__statement._statement)
-        if ret not in (_lib.SQLITE_DONE, _lib.SQLITE_ROW):
+        if ret == _lib.SQLITE_ROW:
+            self.__next_row = self.__fetch_one_row()
+        else:
             self.__statement._reset()
-            raise self.__connection._get_exception(ret)
-        elif ret == _lib.SQLITE_ROW:
-            self.__next_row = self.__fetch_one_row()
+            if ret != _lib.SQLITE_DONE:
+                raise self.__connection._get_exception(ret)
         return next_row
 
     if sys.version_info[0] < 3:

lib_pypy/cffi/api.py

         if key in ffi._parser._declarations:
             tp = ffi._parser._declarations[key]
             BType = ffi._get_cached_btype(tp)
-            value = backendlib.load_function(BType, name)
+            try:
+                value = backendlib.load_function(BType, name)
+            except KeyError:
+                raise AttributeError(name)
             library.__dict__[name] = value
             return
         #

lib_pypy/msvcrt.py

 # PAC: 2010/08 added MS locking for Whoosh
 
 import ctypes
+import errno
 from ctypes_support import standard_c_lib as _c
 from ctypes_support import get_errno
-import errno
 
 try:
     open_osfhandle = _c._open_osfhandle
 except AttributeError: # we are not on windows
     raise ImportError
 
-try: from __pypy__ import builtinify
-except ImportError: builtinify = lambda f: f
+try: from __pypy__ import builtinify, validate_fd
+except ImportError: builtinify = validate_fd = lambda f: f
 
 
 open_osfhandle.argtypes = [ctypes.c_int, ctypes.c_int]
 open_osfhandle.restype = ctypes.c_int
 
-get_osfhandle = _c._get_osfhandle
-get_osfhandle.argtypes = [ctypes.c_int]
-get_osfhandle.restype = ctypes.c_int
+_get_osfhandle = _c._get_osfhandle
+_get_osfhandle.argtypes = [ctypes.c_int]
+_get_osfhandle.restype = ctypes.c_int
+
+@builtinify
+def get_osfhandle(fd):
+    """"get_osfhandle(fd) -> file handle
+
+    Return the file handle for the file descriptor fd. Raises IOError if
+    fd is not recognized."""
+    try:
+        validate_fd(fd)
+    except OSError as e:
+        raise IOError(*e.args)
+    return _get_osfhandle(fd)
 
 setmode = _c._setmode
 setmode.argtypes = [ctypes.c_int, ctypes.c_int]

lib_pypy/pyrepl/python_reader.py

 
     def execute(self, text):
         try:
-            # ooh, look at the hack:            
+            # ooh, look at the hack:
             code = self.compile("# coding:utf8\n"+text.encode('utf-8'),
-                                '<input>', 'single')
+                                '<stdin>', 'single')
         except (OverflowError, SyntaxError, ValueError):
-            self.showsyntaxerror("<input>")
+            self.showsyntaxerror('<stdin>')
         else:
             self.runcode(code)
             if sys.stdout and not sys.stdout.closed:

lib_pypy/pyrepl/simple_interact.py

     import code
     if mainmodule is None:
         import __main__ as mainmodule
-    console = code.InteractiveConsole(mainmodule.__dict__)
+    console = code.InteractiveConsole(mainmodule.__dict__, filename='<stdin>')
 
     def more_lines(unicodetext):
         # ooh, look at the hack:
         src = "#coding:utf-8\n"+unicodetext.encode('utf-8')
         try:
-            code = console.compile(src, '<input>', 'single')
+            code = console.compile(src, '<stdin>', 'single')
         except (OverflowError, SyntaxError, ValueError):
             return False
         else:

pypy/config/pypyoption.py

      "thread", "itertools", "pyexpat", "_ssl", "cpyext", "array",
      "binascii", "_multiprocessing", '_warnings',
      "_collections", "_multibytecodec", "micronumpy", "_ffi",
-     "_continuation", "_cffi_backend", "_csv"]
+     "_continuation", "_cffi_backend", "_csv", "cppyy"]
 ))
 
 translation_modules = default_modules.copy()
     del working_modules["termios"]
     del working_modules["_minimal_curses"]
 
+    del working_modules["cppyy"]  # not tested on win32
+
     # The _locale module is needed by site.py on Windows
     default_modules["_locale"] = None
 
     del working_modules["_minimal_curses"]
     del working_modules["termios"]
     del working_modules["_multiprocessing"]   # depends on rctime
-
+    del working_modules["cppyy"]  # depends on ctypes
 
 
 module_dependencies = {
 
 ::
 
-  pypy <path to rpython>/rpython/bin/rpython -Ojit --platform=arm --gcrootfinder=shadowstack --jit-backend=armv7 targetpypystandalone.py
+  pypy <path to rpython>/rpython/bin/rpython -Ojit --platform=arm --gcrootfinder=shadowstack --jit-backend=arm targetpypystandalone.py
 
 The gcrootfinder option is needed to work around `issue 1377`_ and the jit-backend works around `issue 1376`_
 

pypy/doc/config/translation.gcrootfinder.txt

 - ``--gcrootfinder=asmgcc``: use assembler hackery to find the
   roots directly from the normal stack.  This is a bit faster,
   but platform specific.  It works so far with GCC or MSVC,
-  on i386 and x86-64.
+  on i386 and x86-64.  It is tested only on Linux (where it is
+  the default) so other platforms (as well as MSVC) may need
+  various fixes before they can be used.
 
 You may have to force the use of the shadowstack root finder if
 you are running into troubles or if you insist on translating

pypy/doc/cppyy.rst

 cppyy: C++ bindings for PyPy
 ============================
 
-The cppyy module provides C++ bindings for PyPy by using the reflection
-information extracted from C++ header files by means of the
-`Reflex package`_.
-For this to work, you have to both install Reflex and build PyPy from source,
-as the cppyy module is not enabled by default.
-Note that the development version of cppyy lives in the reflex-support
-branch.
-As indicated by this being a branch, support for Reflex is still
-experimental.
-However, it is functional enough to put it in the hands of those who want
-to give it a try.
-In the medium term, cppyy will move away from Reflex and instead use
-`cling`_ as its backend, which is based on `llvm`_.
-Although that will change the logistics on the generation of reflection
-information, it will not change the python-side interface.
+The cppyy module creates, at run-time, Python-side classes and functions for
+C++, by querying a C++ reflection system.
+The default system used is `Reflex`_, which extracts the needed information
+from C++ header files.
+Another current backend is based on `CINT`_, and yet another, more important
+one for the medium- to long-term will be based on `cling`_.
+The latter sits on top of `llvm`_'s `clang`_, and will therefore allow the use
+of C++11.
+The work on the cling backend has so far been done only for CPython, but
+bringing it to PyPy is a lot less work than developing it in the first place.
 
-.. _`Reflex package`: http://root.cern.ch/drupal/content/reflex
+.. _`Reflex`: http://root.cern.ch/drupal/content/reflex
+.. _`CINT`: http://root.cern.ch/drupal/content/cint
 .. _`cling`: http://root.cern.ch/drupal/content/cling
 .. _`llvm`: http://llvm.org/
+.. _`clang`: http://clang.llvm.org/
+
+This document describes the version of cppyy that lives in the main branch of
+PyPy.
+The development of cppyy happens in the "reflex-support" branch.
 
 
 Motivation
 ==========
 
-The cppyy module offers two unique features, which result in great
-performance as well as better functionality and cross-language integration
-than would otherwise be possible.
-First, cppyy is written in RPython and therefore open to optimizations by the
-JIT up until the actual point of call into C++.
-This means that there are no conversions necessary between a garbage collected
-and a reference counted environment, as is needed for the use of existing
-extension modules written or generated for CPython.
-It also means that if variables are already unboxed by the JIT, they can be
-passed through directly to C++.
-Second, Reflex (and cling far more so) adds dynamic features to C++, thus
-greatly reducing impedance mismatches between the two languages.
-In fact, Reflex is dynamic enough that you could write the runtime bindings
+To provide bindings to another language in CPython, you program to a
+generic C-API that exposes many of the interpreter features.
+With PyPy, however, there is no such generic C-API, because several of the
+interpreter features (e.g. the memory model) are pluggable and therefore
+subject to change.
+Furthermore, a generic API does not allow any assumptions about the calls
+into another language, forcing the JIT to behave conservatively around these
+calls and with the objects that cross language boundaries.
+In contrast, cppyy does not expose an API, but expects one to be implemented
+by a backend.
+It makes strong assumptions about the semantics of the API that it uses and
+that in turn allows the JIT to make equally strong assumptions.
+This is possible, because the expected API is only for providing C++ language
+bindings, and does not provide generic programmability.
+
+The cppyy module further offers two features, which result in improved
+performance as well as better functionality and cross-language integration.
+First, cppyy itself is written in RPython and therefore open to optimizations
+by the JIT up until the actual point of call into C++.
+This means for example, that if variables are already unboxed by the JIT, they
+can be passed through directly to C++.
+Second, a backend such as Reflex (and cling far more so) adds dynamic features
+to C++, thus greatly reducing impedance mismatches between the two languages.
+For example, Reflex is dynamic enough to allow writing runtime bindings
 generation in python (as opposed to RPython) and this is used to create very
 natural "pythonizations" of the bound code.
+As another example, cling allows automatic instantiations of templates.
+
+See this description of the `cppyy architecture`_ for further details.
+
+.. _`cppyy architecture`: http://morepypy.blogspot.com/2012/06/architecture-of-cppyy.html
 
 
 Installation
 ============
 
-For now, the easiest way of getting the latest version of Reflex, is by
-installing the ROOT package.
-Besides getting the latest version of Reflex, another advantage is that with
-the full ROOT package, you can also use your Reflex-bound code on `CPython`_.
-`Download`_ a binary or install from `source`_.
-Some Linux and Mac systems may have ROOT provided in the list of scientific
-software of their packager.
-If, however, you prefer a standalone version of Reflex, the best is to get
-this `recent snapshot`_, and install like so::
+There are two ways of using cppyy, and the choice depends on how pypy-c was
+built: the backend can be builtin, or dynamically loadable.
+The former has the disadvantage of requiring pypy-c to be linked with external
+C++ libraries (e.g. libReflex.so), but has the advantage of being faster in
+some cases.
+That advantage will disappear over time, however, with improvements in the
+JIT.
+Therefore, this document assumes that the dynamically loadable backend is
+chosen (it is, by default).
+See the `backend documentation`_.
 
-    $ tar jxf reflex-2012-05-02.tar.bz2
-    $ cd reflex-2012-05-02
-    $ build/autogen
+.. _`backend documentation`: cppyy_backend.html
+
+A standalone version of Reflex that also provides the dynamically loadable
+backend is available for `download`_.
+That version, as well as any other distribution of Reflex (e.g. the one that
+comes with `ROOT`_, which may be part of your Linux distribution as part of
+the selection of scientific software) will also work for a build with the
+builtin backend.
+
+.. _`download`: http://cern.ch/wlav/reflex-2013-04-23.tar.bz2
+.. _`ROOT`: http://root.cern.ch/
+
+Besides Reflex, you probably need a version of `gccxml`_ installed, which is
+most easily provided by the packager of your system.
+If you read up on gccxml, you will probably notice that it is no longer being
+developed and hence will not provide C++11 support.
+That's why the medium term plan is to move to cling.
+Note that gccxml is only needed to generate reflection libraries.
+It is not needed to use them.
+
+.. _`gccxml`: http://www.gccxml.org
+
+To install the standalone version of Reflex, after download::
+
+    $ tar jxf reflex-2013-04-23.tar.bz2
+    $ cd reflex-2013-04-23
+    $ ./build/autogen
     $ ./configure <usual set of options such as --prefix>
     $ make && make install
 
-Also, make sure you have a version of `gccxml`_ installed, which is most
-easily provided by the packager of your system.
-If you read up on gccxml, you'll probably notice that it is no longer being
-developed and hence will not provide C++11 support.
-That's why the medium term plan is to move to `cling`_.
+The usual rules apply: <prefix>/bin needs to be added to the ``PATH`` and
+<prefix>/lib to the ``LD_LIBRARY_PATH`` environment variable.
+For convenience, this document will assume that there is a ``REFLEXHOME``
+variable that points to <prefix>.
+If you downloaded or built the whole of ROOT, ``REFLEXHOME`` should be equal
+to ``ROOTSYS``.
 
-.. _`Download`: http://root.cern.ch/drupal/content/downloading-root
-.. _`source`: http://root.cern.ch/drupal/content/installing-root-source
-.. _`recent snapshot`: http://cern.ch/wlav/reflex-2012-05-02.tar.bz2
-.. _`gccxml`: http://www.gccxml.org
+The following is optional, and is only to show how pypy-c can be build
+`from source`_, for example to get at the main development branch of cppyy.
+The `backend documentation`_ has more details on the backend-specific
+prerequisites.
 
-Next, get the `PyPy sources`_, optionally select the reflex-support branch,
-and build it.
-For the build to succeed, the ``$ROOTSYS`` environment variable must point to
-the location of your ROOT (or standalone Reflex) installation, or the
-``root-config`` utility must be accessible through ``PATH`` (e.g. by adding
-``$ROOTSYS/bin`` to ``PATH``).
-In case of the former, include files are expected under ``$ROOTSYS/include``
-and libraries under ``$ROOTSYS/lib``.
 Then run the translation to build ``pypy-c``::
 
     $ hg clone https://bitbucket.org/pypy/pypy
     $ cd pypy
     $ hg up reflex-support         # optional
-    $ cd pypy/goal
     
     # This example shows python, but using pypy-c is faster and uses less memory
-    $ python ../../rpython/bin/rpython.py -O jit --gcrootfinder=shadowstack targetpypystandalone.py --withmod-cppyy
+    $ python rpython/translator/goal/translate.py --opt=jit pypy/goal/targetpypystandalone --withmod-cppyy
 
 This will build a ``pypy-c`` that includes the cppyy module, and through that,
 Reflex support.
 If not, you may want `to obtain a binary distribution`_ to speed up the
 translation step.
 
-.. _`PyPy sources`: https://bitbucket.org/pypy/pypy/overview
+.. _`from source`: https://bitbucket.org/pypy/pypy/overview
 .. _`to obtain a binary distribution`: http://doc.pypy.org/en/latest/getting-started.html#download-a-pre-built-pypy
 
 
-Basic example
-=============
+Basic bindings example
+======================
 
 Now test with a trivial example whether all packages are properly installed
 and functional.
 code::
 
     $ genreflex MyClass.h
-    $ g++ -fPIC -rdynamic -O2 -shared -I$ROOTSYS/include MyClass_rflx.cpp -o libMyClassDict.so -L$ROOTSYS/lib -lReflex
+    $ g++ -fPIC -rdynamic -O2 -shared -I$REFLEXHOME/include MyClass_rflx.cpp -o libMyClassDict.so -L$REFLEXHOME/lib -lReflex
 
 Now you're ready to use the bindings.
 Since the bindings are designed to look pythonistic, it should be
 For example::
 
     $ genreflex MyClass.h --rootmap=libMyClassDict.rootmap --rootmap-lib=libMyClassDict.so
-    $ g++ -fPIC -rdynamic -O2 -shared -I$ROOTSYS/include MyClass_rflx.cpp -o libMyClassDict.so -L$ROOTSYS/lib -lReflex
+    $ g++ -fPIC -rdynamic -O2 -shared -I$REFLEXHOME/include MyClass_rflx.cpp -o libMyClassDict.so -L$REFLEXHOME/lib -lReflex
 
 where the first option (``--rootmap``) specifies the output file name, and the
 second option (``--rootmap-lib``) the name of the reflection library where
 Now the reflection info can be generated and compiled::
 
     $ genreflex MyAdvanced.h --selection=MyAdvanced.xml
-    $ g++ -fPIC -rdynamic -O2 -shared -I$ROOTSYS/include MyAdvanced_rflx.cpp -o libAdvExDict.so -L$ROOTSYS/lib -lReflex
+    $ g++ -fPIC -rdynamic -O2 -shared -I$REFLEXHOME/include MyAdvanced_rflx.cpp -o libAdvExDict.so -L$REFLEXHOME/lib -lReflex
 
 and subsequently be used from PyPy::
 
 bound using::
 
     $ genreflex example.h --deep --rootmap=libexampleDict.rootmap --rootmap-lib=libexampleDict.so
-    $ g++ -fPIC -rdynamic -O2 -shared -I$ROOTSYS/include example_rflx.cpp -o libexampleDict.so -L$ROOTSYS/lib -lReflex
+    $ g++ -fPIC -rdynamic -O2 -shared -I$REFLEXHOME/include example_rflx.cpp -o libexampleDict.so -L$REFLEXHOME/lib -lReflex
 
 .. _`example code`: cppyy_example.html
 
   All template classes must already exist in the loaded reflection info, they
   do not work (yet) with the class loader.
 
+  For compatibility with other bindings generators, use of square brackets
+  instead of parenthesis to instantiate templates is supported as well.
+
+* **templated functions**: Automatically participate in overloading and are
+  used in the same way as other global functions.
+
+* **templated methods**: For now, require an explicit selection of the
+  template parameters.
+  This will be changed to allow them to participate in overloads as expected.
+
 * **typedefs**: Are simple python references to the actual classes to which
   they refer.
 
 Run the normal ``genreflex`` and compilation steps::
 
     $ genreflex MyTemplate.h --selection=MyTemplate.xml
-    $ g++ -fPIC -rdynamic -O2 -shared -I$ROOTSYS/include MyTemplate_rflx.cpp -o libTemplateDict.so -L$ROOTSYS/lib -lReflex
+    $ g++ -fPIC -rdynamic -O2 -shared -I$REFLEXHOME/include MyTemplate_rflx.cpp -o libTemplateDict.so -L$REFLEXHOME/lib -lReflex
 
 Note: this is a dirty corner that clearly could do with some automation,
 even if the macro already helps.
 The fast lane
 =============
 
-The following is an experimental feature of cppyy, and that makes it doubly
-experimental, so caveat emptor.
+The following is an experimental feature of cppyy.
+It mostly works, but there are some known issues (e.g. with return-by-value).
+Soon it should be the default mode, however.
+
 With a slight modification of Reflex, it can provide function pointers for
 C++ methods, and hence allow PyPy to call those pointers directly, rather than
 calling C++ through a Reflex stub.
-This results in a rather significant speed-up.
-Mind you, the normal stub path is not exactly slow, so for now only use this
-out of curiosity or if you really need it.
 
-To install this patch of Reflex, locate the file genreflex-methptrgetter.patch
-in pypy/module/cppyy and apply it to the genreflex python scripts found in
-``$ROOTSYS/lib``::
+The standalone version of Reflex `provided`_ has been patched, but if you get
+Reflex from another source (most likely with a ROOT distribution), locate the
+file `genreflex-methptrgetter.patch`_ in pypy/module/cppyy and apply it to
+the genreflex python scripts found in ``$ROOTSYS/lib``::
 
     $ cd $ROOTSYS/lib
     $ patch -p2 < genreflex-methptrgetter.patch
 ``-Wno-pmf-conversions`` option to ``g++`` when compiling.
 The rest works the same way: the fast path will be used transparently (which
 also means that you can't actually find out whether it is in use, other than
-by running a micro-benchmark).
+by running a micro-benchmark or a JIT test).
 
+.. _`provided`: http://cern.ch/wlav/reflex-2013-04-23.tar.bz2
+.. _`genreflex-methptrgetter.patch`: https://bitbucket.org/pypy/pypy/src/default/pypy/module/cppyy/genreflex-methptrgetter.patch
 
 CPython
 =======

pypy/doc/cppyy_backend.rst

+==================
+Backends for cppyy
+==================
+
+The cppyy module needs a backend to provide the C++ reflection information on
+which the Python bindings are build.
+The backend is called through a C-API, which can be found in the PyPy sources
+in: `pypy/module/cppyy/include/capi.h`_.
+There are two kinds of API calls: querying about reflection information, which
+are used during the creation of Python-side constructs, and making the actual
+calls into C++.
+The objects passed around are all opaque: cppyy does not make any assumptions
+about them, other than that the opaque handles can be copied.
+Their definition, however, appears in two places: in the C code (in capi.h),
+and on the RPython side (in `capi_types.py`_), so if they are changed, they
+need to be changed on both sides.
+
+.. _`pypy/module/cppyy/include/capi.h`: https://bitbucket.org/pypy/pypy/src/default/pypy/module/cppyy/include/capi.h
+.. _`capi_types.py`: https://bitbucket.org/pypy/pypy/src/default/pypy/module/cppyy/capi/capi_types.py
+
+There are two places where selections in the RPython code affect the choice
+(and use) of the backend.
+The first is in `pypy/module/cppyy/capi/__init__.py`_::
+
+    # choose C-API access method:
+    from pypy.module.cppyy.capi.loadable_capi import *
+    #from pypy.module.cppyy.capi.builtin_capi import *
+
+The default is the loadable C-API.
+Comment it and uncomment the builtin C-API line, to use the builtin version.
+
+.. _`pypy/module/cppyy/capi/__init__.py`:  https://bitbucket.org/pypy/pypy/src/default/pypy/module/cppyy/capi/__init__.py
+
+Next, if the builtin C-API is chosen, the specific backend needs to be set as
+well (default is Reflex).
+This second choice is in `pypy/module/cppyy/capi/builtin_capi.py`_::
+
+    import reflex_capi as backend
+    #import cint_capi as backend
+
+After those choices have been made, built pypy-c as usual.
+
+.. _`pypy/module/cppyy/capi/builtin_capi.py`:  https://bitbucket.org/pypy/pypy/src/default/pypy/module/cppyy/capi/builtin_capi.py
+
+When building pypy-c from source, keep the following in mind.
+If the loadable_capi is chosen, no further prerequisites are needed.
+However, for the build of the builtin_capi to succeed, the ``ROOTSYS``
+environment variable must point to the location of your ROOT (or standalone
+Reflex in the case of the Reflex backend) installation, or the ``root-config``
+utility must be accessible through ``$PATH`` (e.g. by adding ``$ROOTSYS/bin``
+to ``PATH``).
+In case of the former, include files are expected under ``$ROOTSYS/include``
+and libraries under ``$ROOTSYS/lib``.

pypy/doc/index.rst

 .. _`Starting with RPython`: getting-started-dev.html
 .. _`how to contribute`: how-to-contribute.html
 .. _`PyPy website`: http://pypy.org
+.. _`LICENSE`: https://bitbucket.org/pypy/pypy/src/default/LICENSE
 
 Index of various topics:
 ========================
   * `Sandboxing Python code`_
   * `Garbage collection environment variables`_
 
-Status_ of the project.
-
 .. _`Differences between PyPy and CPython`: cpython_differences.html
 .. _`What PyPy can do for your objects`: objspace-proxies.html
-.. _`Continulets and greenlets_`: stackless.html
+.. _`Continulets and greenlets`: stackless.html
 .. _`JIT Generation in PyPy`: jit/index.html
 .. _`JIT hooks`: jit-hooks.html
 .. _`Sandboxing Python code`: sandbox.html

pypy/doc/whatsnew-head.rst

 Rudimentary support for bytearray in RPython
 
 .. branch: refactor-call_release_gil
-Fix a bug which casused cffi to return the wrong result when calling a C
+Fix a bug which caused cffi to return the wrong result when calling a C
 function which calls a Python callback which forces the frames
 
 .. branch: virtual-raw-mallocs
-JIT optimizations which makes cffi calls even faster, by removing the need to
+JIT optimizations which make cffi calls even faster, by removing the need to
 allocate a temporary buffer where to store the arguments.
 
+.. branch: improve-docs-2
+Improve documents and straighten out links
+
+.. branch: fast-newarray
+Inline the fast path of newarray in the assembler.
+Disabled on ARM until we fix issues.
+
+.. branch: reflex-support
+Allow dynamic loading of a (Reflex) backend that implements the C-API needed
+to provide reflection information
+
 .. branches we don't care about
 .. branch: autoreds
-.. branch: reflex-support
 .. branch: kill-faking
 .. branch: improved_ebnfparse_error
 .. branch: task-decorator
 
 .. branch: release-2.0-beta2
 .. branch: unbreak-freebsd
+
+.. branch: virtualref-virtualizable

pypy/interpreter/astcompiler/consts.py

 CO_FUTURE_WITH_STATEMENT = 0x8000
 CO_FUTURE_PRINT_FUNCTION = 0x10000
 CO_FUTURE_UNICODE_LITERALS = 0x20000
-CO_CONTAINSGLOBALS = 0x80000 # pypy-specific: need to check that it's not used
-                             # by any other flag
 
 PyCF_SOURCE_IS_UTF8 = 0x0100
 PyCF_DONT_IMPLY_DEDENT = 0x0200

pypy/interpreter/pycode.py

 from pypy.interpreter.gateway import unwrap_spec
 from pypy.interpreter.astcompiler.consts import (
     CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS, CO_NESTED,
-    CO_GENERATOR, CO_CONTAINSGLOBALS)
+    CO_GENERATOR)
 from pypy.tool.stdlib_opcode import opcodedesc, HAVE_ARGUMENT
 from rpython.rlib.rarithmetic import intmask
 from rpython.rlib.objectmodel import compute_hash
         self._initialize()
 
     def _initialize(self):
-        self._init_flags()
-
         if self.co_cellvars:
             argcount = self.co_argcount
             assert argcount >= 0     # annotator hint
             '__pypy__' not in sys.builtin_module_names):
             raise Exception("CPython host codes should not be rendered")
 
-    def _init_flags(self):
-        co_code = self.co_code
-        next_instr = 0
-        while next_instr < len(co_code):
-            opcode = ord(co_code[next_instr])
-            next_instr += 1
-            if opcode >= HAVE_ARGUMENT:
-                next_instr += 2
-            while opcode == opcodedesc.EXTENDED_ARG.index:
-                opcode = ord(co_code[next_instr])
-                next_instr += 3
-            if opcode == opcodedesc.LOAD_GLOBAL.index:
-                self.co_flags |= CO_CONTAINSGLOBALS
-            elif opcode == opcodedesc.LOAD_NAME.index:
-                self.co_flags |= CO_CONTAINSGLOBALS
-
     co_names = property(lambda self: [self.space.unwrap(w_name) for w_name in self.co_names_w]) # for trace
 
     def signature(self):

pypy/interpreter/pyopcode.py

                                              "code=%d, name=%s" %
                                              (self.last_instr, opcode,
                                               methodname))
-                try:
-                    res = meth(oparg, next_instr)
-                except Exception:
-                    if 0:
-                        import dis, sys
-                        print "*** %s at offset %d (%s)" % (sys.exc_info()[0],
-                                                            self.last_instr,
-                                                            methodname)
-                        try:
-                            dis.dis(co_code)
-                        except:
-                            pass
-                    raise
+                res = meth(oparg, next_instr)
                 if res is not None:
                     next_instr = res
 

pypy/interpreter/test/test_code.py

             filename = filename[:-1]
 
         cls.w_file = cls.space.wrap(filename)
-        cls.w_CO_CONTAINSGLOBALS = cls.space.wrap(consts.CO_CONTAINSGLOBALS)
 
     def test_attributes(self):
         def f(): pass
         # CO_NESTED
         assert f(4).func_code.co_flags & 0x10
         assert f.func_code.co_flags & 0x10 == 0
-        # check for CO_CONTAINSGLOBALS
-        assert not f.func_code.co_flags & self.CO_CONTAINSGLOBALS
-
-
-        exec """if 1:
-        r = range
-        def f():
-            return [l for l in r(100)]
-        def g():
-            return [l for l in [1, 2, 3, 4]]
-"""
-
-        # check for CO_CONTAINSGLOBALS
-        assert f.func_code.co_flags & self.CO_CONTAINSGLOBALS
-        assert not g.func_code.co_flags & self.CO_CONTAINSGLOBALS
-
-        exec """if 1:
-        b = 2
-        def f(x):
-            exec "a = 1";
-            return a + b + x
-"""
-        # check for CO_CONTAINSGLOBALS
-        assert f.func_code.co_flags & self.CO_CONTAINSGLOBALS

pypy/interpreter/test/test_compiler.py

 
 class AppTestOptimizer:
 
+    def setup_class(cls):
+        cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
+
     def test_remove_ending(self):
         source = """def f():
             return 3
     def test_none_constant(self):
         import opcode
         co = compile("def f(): return None", "<test>", "exec").co_consts[0]
-        assert "None" not in co.co_names
+        if not self.runappdirect:  # This is a pypy optimization
+            assert "None" not in co.co_names
         co = co.co_code
         op = ord(co[0]) + (ord(co[1]) << 8)
         assert op == opcode.opmap["LOAD_CONST"]
         def code(source):
             return compile(source, "<test>", "exec")
         co = code("x = 10//4")
-        assert len(co.co_consts) == 2
-        assert co.co_consts[0] == 2
+        if self.runappdirect:
+            assert 2 in co.co_consts
+        else:
+            # PyPy is more precise
+            assert len(co.co_consts) == 2
+            assert co.co_consts[0] == 2
         co = code("x = 10/4")
         assert len(co.co_consts) == 3
         assert co.co_consts[:2] == (10, 4)
         co = code("from __future__ import division\nx = 10/4")
-        assert co.co_consts[2] == 2.5
+        if self.runappdirect:
+            assert 2.5 in co.co_consts
+        else:
+            assert co.co_consts[2] == 2.5
 
     def test_tuple_folding(self):
         co = compile("x = (1, 2, 3)", "<test>", "exec")
-        assert co.co_consts == ((1, 2, 3), None)
+        if not self.runappdirect:
+            # PyPy is more precise
+            assert co.co_consts == ((1, 2, 3), None)
+        else:
+            assert (1, 2, 3) in co.co_consts
+            assert None in co.co_consts
         co = compile("x = ()", "<test>", "exec")
-        assert co.co_consts == ((), None)
+        assert set(co.co_consts) == set(((), None))
 
     def test_unary_folding(self):
+        def check_const(co, value):
+            assert value in co.co_consts
+            if not self.runappdirect:
+                # This is a pypy optimization
+                assert co.co_consts[0] == value
         co = compile("x = -(3)", "<test>", "exec")
-        assert co.co_consts[0] == -3
+        check_const(co, -3)
         co = compile("x = ~3", "<test>", "exec")
-        assert co.co_consts[0] == ~3
+        check_const(co, ~3)
         co = compile("x = +(-3)", "<test>", "exec")
-        assert co.co_consts[0] == -3
+        check_const(co, -3)
         co = compile("x = not None", "<test>", "exec")
-        assert co.co_consts[0] is True
+        if not self.runappdirect:
+            # CPython does not have this optimization
+            assert co.co_consts == (True, None)
 
     def test_folding_of_binops_on_constants(self):
         def disassemble(func):

pypy/module/__pypy__/test/test_signal.py

             __pypy__.thread._signals_enter()
 
     def test_enable_signals(self):
-        import __pypy__, thread, signal, time
+        import __pypy__, thread, signal, time, sys
 
         def subthread():
             try:
         # This is normally called by app_main.py
         signal.signal(signal.SIGINT, signal.default_int_handler)
 
+        if sys.platform.startswith('win'):
+            # Windows seems to hang on _setmode when the first print comes from
+            # a thread, so make sure we've initialized io
+            sys.stdout
+
         for i in range(10):
             __pypy__.thread._signals_exit()
             try:
                 done = []
                 interrupted = []
                 thread.start_new_thread(subthread, ())
-                for i in range(10):
+                for j in range(10):
                     if len(done): break
                     print '.'
                     time.sleep(0.1)
             py.test.skip("this is only a test for -A runs on top of pypy")
 
     def test_enable_signals(self):
-        import __pypy__, thread, signal, time
+        import __pypy__, thread, time
 
         interrupted = []
         lock = thread.allocate_lock()
Add a comment to this file

pypy/module/_cffi_backend/ccallback.py

File contents unchanged.

pypy/module/_cffi_backend/cdataobj.py

 W_CData.typedef = TypeDef(
     'CData',
     __module__ = '_cffi_backend',
+    __name__ = '<cdata>',
     __repr__ = interp2app(W_CData.repr),
     __nonzero__ = interp2app(W_CData.nonzero),
     __int__ = interp2app(W_CData.int),
Add a comment to this file

pypy/module/_cffi_backend/ctypeprim.py

File contents unchanged.

Add a comment to this file

pypy/module/_cffi_backend/ctypestruct.py

File contents unchanged.

Add a comment to this file

pypy/module/_cffi_backend/misc.py

File contents unchanged.

pypy/module/_cffi_backend/test/_backend_test_c.py

     c[1:3] = d
     assert list(c) == [0, 40, 50, 30, 0]
 
+def test_cdata_name_module_doc():
+    p = new_primitive_type("signed char")
+    x = cast(p, 17)
+    assert x.__module__ == '_cffi_backend'
+    assert x.__name__ == '<cdata>'
+    assert hasattr(x, '__doc__')
+
 def test_version():
     # this test is here mostly for PyPy
     assert __version__ == "0.6"

pypy/module/_io/interp_bytesio.py

     TypeDef, generic_new_descr, GetSetProperty)
 from pypy.interpreter.gateway import interp2app, unwrap_spec
 from pypy.interpreter.error import OperationError, operationerrfmt
+from rpython.rlib.rStringIO import RStringIO
 from rpython.rlib.rarithmetic import r_longlong
 from pypy.module._io.interp_bufferedio import W_BufferedIOBase
 from pypy.module._io.interp_iobase import convert_size
 import sys
 
-def buffer2string(buffer, start, end):
-    from rpython.rlib.rstring import StringBuilder
-    builder = StringBuilder(end - start)
-    for i in range(start, end):
-        builder.append(buffer[i])
-    return builder.build()
 
-class W_BytesIO(W_BufferedIOBase):
+class W_BytesIO(RStringIO, W_BufferedIOBase):
     def __init__(self, space):
         W_BufferedIOBase.__init__(self, space)
-        self.pos = 0
-        self.string_size = 0
-        self.buf = None
+        self.init()
 
     def descr_init(self, space, w_initial_bytes=None):
-        # In case __init__ is called multiple times
-        self.buf = []
-        self.string_size = 0
-        self.pos = 0
-
+        self.init()
         if not space.is_none(w_initial_bytes):
             self.write_w(space, w_initial_bytes)
-            self.pos = 0
+            self.seek(0)
 
     def _check_closed(self, space, message=None):
-        if self.buf is None:
+        if self.is_closed():
             if message is None:
                 message = "I/O operation on closed file"
             raise OperationError(space.w_ValueError, space.wrap(message))
     def read_w(self, space, w_size=None):
         self._check_closed(space)
         size = convert_size(space, w_size)
-
-        # adjust invalid sizes
-        available = self.string_size - self.pos
-        if not 0 <= size <= available:
-            size = available
-            if size < 0:
-                size = 0
-
-        output = buffer2string(self.buf, self.pos, self.pos + size)
-        self.pos += size
-        return space.wrap(output)
+        return space.wrap(self.read(size))
 
     def readline_w(self, space, w_limit=None):
         self._check_closed(space)
         limit = convert_size(space, w_limit)
-
-        cur_pos = self.pos
-        if limit < 0:
-            end_pos = self.string_size
-        else:
-            end_pos = min(cur_pos + limit, self.string_size)
-        while cur_pos != end_pos:
-            if self.buf[cur_pos] == '\n':
-                cur_pos += 1
-                break
-            cur_pos += 1
-
-        output = buffer2string(self.buf, self.pos, cur_pos)
-        self.pos = cur_pos
-        return space.wrap(output)
+        return space.wrap(self.readline(limit))
 
     def read1_w(self, space, w_size):
         return self.read_w(space, w_size)
         rwbuffer = space.rwbuffer_w(w_buffer)
         size = rwbuffer.getlength()
 
-        if self.pos + size > self.string_size:
-            size = self.string_size - self.pos
-
-        output = buffer2string(self.buf, self.pos, self.pos + size)
-        length = len(output)
+        output = self.read(size)
         rwbuffer.setslice(0, output)
-        self.pos += length
-        return space.wrap(length)
+        return space.wrap(len(output))
 
     def write_w(self, space, w_data):
         self._check_closed(space)
         if space.isinstance_w(w_data, space.w_unicode):
             raise OperationError(space.w_TypeError, space.wrap(
                 "bytes string of buffer expected"))
-        buf = space.buffer_w(w_data)
-        length = buf.getlength()
+        buf = space.bufferstr_w(w_data)
+        length = len(buf)
         if length <= 0:
-            return
-
-        if self.pos + length > len(self.buf):
-            self.buf.extend(['\0'] * (self.pos + length - len(self.buf)))
-
-        if self.pos > self.string_size:
-            # In case of overseek, pad with null bytes the buffer region
-            # between the end of stream and the current position.
-            #
-            # 0   lo      string_size                           hi
-            # |   |<---used--->|<----------available----------->|
-            # |   |            <--to pad-->|<---to write--->    |
-            # 0   buf                   position
-            for i in range(self.string_size, self.pos):
-                self.buf[i] = '\0'
-
-        # Copy the data to the internal buffer, overwriting some of the
-        # existing data if self->pos < self->string_size.
-        for i in range(length):
-            self.buf[self.pos + i] = buf.getitem(i)
-        self.pos += length
-
-        # Set the new length of the internal string if it has changed
-        if self.string_size < self.pos:
-            self.string_size = self.pos
-
+            return space.wrap(0)
+        self.write(buf)
         return space.wrap(length)
 
     def truncate_w(self, space, w_size=None):
         self._check_closed(space)
 
+        pos = self.tell()
         if space.is_none(w_size):
-            size = self.pos
+            size = pos
         else:
             size = space.r_longlong_w(w_size)
 
             raise OperationError(space.w_ValueError, space.wrap(
                 "negative size value"))
 
-        if size < self.string_size:
-            self.string_size = size
-            del self.buf[size:]
-
+        self.truncate(size)
+        if size == pos:
+            self.seek(0, 2)
+        else:
+            self.seek(pos)
         return space.wrap(size)
 
     def getvalue_w(self, space):
         self._check_closed(space)
-        return space.wrap(buffer2string(self.buf, 0, self.string_size))
+        return space.wrap(self.getvalue())
 
     def tell_w(self, space):
         self._check_closed(space)
-        return space.wrap(self.pos)
+        return space.wrap(self.tell())
 
     @unwrap_spec(pos=r_longlong, whence=int)
     def seek_w(self, space, pos, whence=0):
                 raise OperationError(space.w_ValueError, space.wrap(
                     "negative seek value"))
         elif whence == 1:
-            if pos > sys.maxint - self.pos:
+            if pos > sys.maxint - self.tell():
                 raise OperationError(space.w_OverflowError, space.wrap(
                     "new position too large"))
-            pos += self.pos
         elif whence == 2:
-            if pos > sys.maxint - self.string_size:
+            if pos > sys.maxint - self.getsize():
                 raise OperationError(space.w_OverflowError, space.wrap(
                     "new position too large"))
-            pos += self.string_size
         else:
             raise operationerrfmt(space.w_ValueError,
                 "whence must be between 0 and 2, not %d", whence)
 
-        if pos >= 0:
-            self.pos = pos
-        else:
-            self.pos = 0
-        return space.wrap(self.pos)
+        self.seek(pos, whence)
+        return space.wrap(self.tell())
 
     def readable_w(self, space):
         return space.w_True
         return space.w_True
 
     def close_w(self, space):
-        self.buf = None
+        self.close()
 
     def closed_get_w(self, space):
-        return space.wrap(self.buf is None)
+        return space.wrap(self.is_closed())
 
     def getstate_w(self, space):
         self._check_closed(space)
-        w_content = space.wrap(buffer2string(self.buf, 0, self.string_size))
         return space.newtuple([
-            w_content,
-            space.wrap(self.pos),
+            space.wrap(self.getvalue()),
+            space.wrap(self.tell()),
             self.getdict(space)])
 
     def setstate_w(self, space, w_state):
                 space.type(w_state).getname(space)
             )
         w_content, w_pos, w_dict = space.unpackiterable(w_state, 3)
+        self.truncate(0)
+        self.write_w(space, w_content)
         pos = space.int_w(w_pos)
-        self.buf = []
-        self.write_w(space, w_content)
         if pos < 0:
             raise OperationError(space.w_ValueError, space.wrap(
                 "position value cannot be negative"))
-        self.pos = pos
+        self.seek(pos)
         if not space.is_w(w_dict, space.w_None):
             space.call_method(self.getdict(space), "update", w_dict)
 

pypy/module/_io/interp_stringio.py

         self.pos = end
         return space.wrap(u''.join(self.buf[start:end]))
 
-    @unwrap_spec(limit=int)
-    def readline_w(self, space, limit=-1):
+    def readline_w(self, space, w_limit=None):
         self._check_closed(space)
+        limit = convert_size(space, w_limit)
 
         if self.pos >= len(self.buf):
             return space.wrap(u"")

pypy/module/_io/interp_textio.py

-from pypy.module._io.interp_iobase import W_IOBase
-from pypy.interpreter.typedef import (
-    TypeDef, GetSetProperty, interp_attrproperty_w, interp_attrproperty,
-    generic_new_descr)
-from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
+import sys
+
 from pypy.interpreter.baseobjspace import W_Root
 from pypy.interpreter.error import OperationError
-from rpython.rlib.rarithmetic import intmask, r_ulonglong, r_uint
+from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
+from pypy.interpreter.typedef import (
+    GetSetProperty, TypeDef, generic_new_descr, interp_attrproperty,
+    interp_attrproperty_w)
+from pypy.module._codecs import interp_codecs
+from pypy.module._io.interp_iobase import W_IOBase, convert_size
+from rpython.rlib.rarithmetic import intmask, r_uint, r_ulonglong
 from rpython.rlib.rbigint import rbigint
 from rpython.rlib.rstring import UnicodeBuilder
-from pypy.module._codecs import interp_codecs
-from pypy.module._io.interp_iobase import convert_size
-import sys
 
 
 STATE_ZERO, STATE_OK, STATE_DETACHED = range(3)
     errors = GetSetProperty(W_TextIOBase.errors_get_w),
 )
 
+
+def _determine_encoding(space, encoding):
+    if encoding is not None:
+        return space.wrap(encoding)
+
+    try:
+        w_locale = space.call_method(space.builtin, '__import__',
+                                     space.wrap('locale'))
+        w_encoding = space.call_method(w_locale, 'getpreferredencoding')
+    except OperationError as e:
+        # getpreferredencoding() may also raise ImportError
+        if not e.match(space, space.w_ImportError):
+            raise
+        return space.wrap('ascii')
+    else:
+        if space.isinstance_w(w_encoding, space.w_str):
+            return w_encoding
+
+    raise OperationError(space.w_IOError, space.wrap(
+            "could not determine default encoding"))
+
 class PositionCookie(object):
     def __init__(self, bigint):
         self.start_pos = bigint.ulonglongmask()
     def descr_init(self, space, w_buffer, encoding=None,
                    w_errors=None, w_newline=None, line_buffering=0):
         self.state = STATE_ZERO
-
         self.w_buffer = w_buffer
-
-        # Set encoding
-        self.w_encoding = None
-        if encoding is None:
-            try:
-                w_locale = space.call_method(space.builtin, '__import__',
-                                             space.wrap("locale"))
-                self.w_encoding = space.call_method(w_locale,
-                                                    "getpreferredencoding")
-            except OperationError, e:
-                # getpreferredencoding() may also raise ImportError
-                if not e.match(space, space.w_ImportError):
-                    raise
-                self.w_encoding = space.wrap("ascii")
-            else:
-                if not space.isinstance_w(self.w_encoding, space.w_str):
-                    self.w_encoding = None
-        if self.w_encoding:
-            pass
-        elif encoding is not None:
-            self.w_encoding = space.wrap(encoding)
-        else:
-            raise OperationError(space.w_IOError, space.wrap(
-                "could not determine default encoding"))
+        self.w_encoding = _determine_encoding(space, encoding)
 
         if space.is_none(w_errors):
             w_errors = space.wrap("strict")

pypy/module/_io/test/test_bytesio.py

     def test_init(self):
         import _io
         raises(TypeError, _io.BytesIO, u"12345")
+        buf = "1234567890"
+        b = _io.BytesIO(buf)
+        assert b.getvalue() == buf
+        b = _io.BytesIO(None)
+        assert b.getvalue() == ""
+        b.__init__(buf * 2)
+        assert b.getvalue() == buf * 2
+        b.__init__(buf)
+        assert b.getvalue() == buf
 
     def test_init_kwargs(self):
         import _io
     def test_write(self):
         import _io
         f = _io.BytesIO()
+        assert f.write("") == 0
         assert f.write("hello") == 5
         import gc; gc.collect()
         assert f.getvalue() == "hello"
 
     def test_truncate(self):
         import _io
-        f = _io.BytesIO("hello")
+        f = _io.BytesIO()
+        f.write("hello")
+        assert f.truncate(0) == 0
+        assert f.tell() == 5
+        f.seek(0)
+        f.write("hello")
         f.seek(3)
         assert f.truncate() == 3
         assert f.getvalue() == "hel"
+        assert f.truncate(2) == 2
+        assert f.tell() == 3
 
     def test_setstate(self):
         # state is (content, position, __dict__)
         import _io
 
         b = _io.BytesIO("hello")
+        a1 = bytearray('t')
+        a2 = bytearray('testing')
+        assert b.readinto(a1) == 1
+        assert b.readinto(a2) == 4
         b.close()
+        assert a1 == "h"
+        assert a2 == "elloing"
         raises(ValueError, b.readinto, bytearray("hello"))
 
     def test_readline(self):

pypy/module/_io/test/test_stringio.py

         raises(ValueError, sio.read, 1)
         raises(ValueError, sio.write, u"text")
 
-    def testRead(self):
+    def test_read(self):
         import io
         buf = u"1234567890"
         sio = io.StringIO(buf)
         assert buf[5:] == sio.read(900)
         assert u"" == sio.read()
 
+    def test_readline(self):
+        import io
+        sio = io.StringIO(u'123\n456')
+        assert sio.readline(2) == '12'
+        assert sio.readline(None) == '3\n'
+        assert sio.readline() == '456'
+
     def test_seek(self):
         import io
 

pypy/module/_io/test/test_ztranslation.py

+from pypy.objspace.fake.checkmodule import checkmodule
+
+def test_checkmodule():
+    checkmodule('_io')

pypy/module/_minimal_curses/__init__.py

 try:
     import _curses
-except ImportError:
+except Exception:   # probably ImportError or cffi's VerificationError
     try:
-        import _minimal_curses as _curses   # when running on top of pypy-c
+        # when running on top of pypy before it had _curses, settle for minimal
+        # we prefer _curses so any constants added make it into _minimal_curses
+        import _minimal_curses as _curses
     except ImportError:
         import py
-        py.test.skip("no _curses or _minimal_curses module") #no _curses at all
+        py.test.skip("no _curses or _minimal_curses module")  # no _curses at all
 
 from pypy.interpreter.mixedmodule import MixedModule
 from pypy.module._minimal_curses import fficurses  # for side effects

pypy/module/cStringIO/interp_stringio.py

 
 class W_OutputType(RStringIO, W_InputOutputType):
     def __init__(self, space):
-        RStringIO.__init__(self)
+        self.init()
         self.space = space
 
     def descr_truncate(self, w_size=None):
         if size < 0:
             raise OperationError(space.w_IOError, space.wrap("negative size"))
         self.truncate(size)
+        self.seek(0, 2)
 
     @unwrap_spec(buffer='bufferstr')
     def descr_write(self, buffer):

pypy/module/cStringIO/test/test_interp_stringio.py

         f.write(' world')
         f.truncate(30)
         assert f.getvalue() == '\x00' * 20 + 'hello worl'
+        assert f.tell() == 30
+        f.seek(0)
         f.truncate(25)
         assert f.getvalue() == '\x00' * 20 + 'hello'
+        assert f.tell() == 25
         f.write('baz')
         f.write('egg')
         f.truncate(3)

pypy/module/cppyy/__init__.py

         '_resolve_name'          : 'interp_cppyy.resolve_name',
         '_scope_byname'          : 'interp_cppyy.scope_byname',
         '_template_byname'       : 'interp_cppyy.template_byname',
+        '_std_string_name'       : 'interp_cppyy.std_string_name',
         '_set_class_generator'   : 'interp_cppyy.set_class_generator',
         '_register_class'        : 'interp_cppyy.register_class',
+        '_is_static'             : 'interp_cppyy.is_static',
         'CPPInstance'            : 'interp_cppyy.W_CPPInstance',
         'addressof'              : 'interp_cppyy.addressof',
         'bind_object'            : 'interp_cppyy.bind_object',
     }
 
     appleveldefs = {
-        'gbl'                    : 'pythonify.gbl',
+        '_init_pythonify'        : 'pythonify._init_pythonify',
         'load_reflection_info'   : 'pythonify.load_reflection_info',
         'add_pythonization'      : 'pythonify.add_pythonization',
     }
         # code generation is not, so give it a chance to run now
         from pypy.module.cppyy import capi
         capi.register_pythonizations(space)
+
+    def startup(self, space):
+        from pypy.module.cppyy import capi
+        capi.verify_backend(space)      # may raise ImportError
+
+        space.call_method(space.wrap(self), '_init_pythonify')

pypy/module/cppyy/capi/__init__.py

 from rpython.rtyper.lltypesystem import rffi, lltype
-from rpython.rlib import jit
 
-import reflex_capi as backend
-#import cint_capi as backend
+# There are two possible ways of accessing the backend through the reflection
+# C-API: built it into pypy-c, or load it dynamically. The latter is preferred
+# (and is the default) for use with Reflex. B/c of some builtin pythonizations,
+# the former is recommended (for now) with CINT.
 
-identify  = backend.identify
-pythonize = backend.pythonize
-register_pythonizations = backend.register_pythonizations
+# Note: if builtin_capi is chosen, then inside builtin_capi.py, there is still
+# the selection of the desired backend (default is Reflex).
 
-ts_reflect = backend.ts_reflect
-ts_call    = backend.ts_call
-ts_memory  = backend.ts_memory
-ts_helper  = backend.ts_helper
+# choose C-API access method:
+from pypy.module.cppyy.capi.loadable_capi import *
+#from pypy.module.cppyy.capi.builtin_capi import *
 
-_C_OPAQUE_PTR = rffi.LONG
-_C_OPAQUE_NULL = lltype.nullptr(rffi.LONGP.TO)# ALT: _C_OPAQUE_PTR.TO
-
-C_SCOPE = _C_OPAQUE_PTR
-C_NULL_SCOPE = rffi.cast(C_SCOPE, _C_OPAQUE_NULL)
-
-C_TYPE = C_SCOPE
-C_NULL_TYPE = C_NULL_SCOPE
-
-C_OBJECT = _C_OPAQUE_PTR
-C_NULL_OBJECT = rffi.cast(C_OBJECT, _C_OPAQUE_NULL)
-
-C_METHOD = _C_OPAQUE_PTR
-C_INDEX = rffi.LONG
-C_INDEX_ARRAY = rffi.LONGP
-WLAVC_INDEX = rffi.LONG
-
-C_METHPTRGETTER = lltype.FuncType([C_OBJECT], rffi.VOIDP)
-C_METHPTRGETTER_PTR = lltype.Ptr(C_METHPTRGETTER)
+from pypy.module.cppyy.capi.capi_types import C_OBJECT,\
+    C_NULL_TYPE, C_NULL_OBJECT
 
 def direct_ptradd(ptr, offset):
     offset = rffi.cast(rffi.SIZE_T, offset)
 
 def exchange_address(ptr, cif_descr, index):
     return rffi.ptradd(ptr, cif_descr.exchange_args[index])
-
-c_load_dictionary = backend.c_load_dictionary
-
-# name to opaque C++ scope representation ------------------------------------
-_c_num_scopes = rffi.llexternal(
-    "cppyy_num_scopes",
-    [C_SCOPE], rffi.INT,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-def c_num_scopes(cppscope):
-    return _c_num_scopes(cppscope.handle)
-_c_scope_name = rffi.llexternal(
-    "cppyy_scope_name",
-    [C_SCOPE, rffi.INT], rffi.CCHARP,
-    compilation_info = backend.eci)
-def c_scope_name(cppscope, iscope):
-    return charp2str_free(_c_scope_name(cppscope.handle, iscope))
-
-_c_resolve_name = rffi.llexternal(
-    "cppyy_resolve_name",
-    [rffi.CCHARP], rffi.CCHARP,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-def c_resolve_name(name):
-    return charp2str_free(_c_resolve_name(name))
-c_get_scope_opaque = rffi.llexternal(
-    "cppyy_get_scope",
-    [rffi.CCHARP], C_SCOPE,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-c_get_template = rffi.llexternal(
-    "cppyy_get_template",
-    [rffi.CCHARP], C_TYPE,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-_c_actual_class = rffi.llexternal(
-    "cppyy_actual_class",
-    [C_TYPE, C_OBJECT], C_TYPE,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-def c_actual_class(cppclass, cppobj):
-    return _c_actual_class(cppclass.handle, cppobj)
-
-# memory management ----------------------------------------------------------
-_c_allocate = rffi.llexternal(
-    "cppyy_allocate",
-    [C_TYPE], C_OBJECT,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci)
-def c_allocate(cppclass):
-    return _c_allocate(cppclass.handle)
-_c_deallocate = rffi.llexternal(
-    "cppyy_deallocate",
-    [C_TYPE, C_OBJECT], lltype.Void,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci)
-def c_deallocate(cppclass, cppobject):
-    _c_deallocate(cppclass.handle, cppobject)
-_c_destruct = rffi.llexternal(
-    "cppyy_destruct",
-    [C_TYPE, C_OBJECT], lltype.Void,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-def c_destruct(cppclass, cppobject):
-    _c_destruct(cppclass.handle, cppobject)
-
-# method/function dispatching ------------------------------------------------
-c_call_v = rffi.llexternal(
-    "cppyy_call_v",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], lltype.Void,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_b = rffi.llexternal(
-    "cppyy_call_b",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.UCHAR,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_c = rffi.llexternal(
-    "cppyy_call_c",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.CHAR,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_h = rffi.llexternal(
-    "cppyy_call_h",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.SHORT,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_i = rffi.llexternal(
-    "cppyy_call_i",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.INT,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_l = rffi.llexternal(
-    "cppyy_call_l",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.LONG,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_ll = rffi.llexternal(
-    "cppyy_call_ll",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.LONGLONG,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_f = rffi.llexternal(
-    "cppyy_call_f",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.FLOAT,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_d = rffi.llexternal(
-    "cppyy_call_d",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.DOUBLE,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-
-c_call_r = rffi.llexternal(
-    "cppyy_call_r",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.VOIDP,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-c_call_s = rffi.llexternal(
-    "cppyy_call_s",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], rffi.CCHARP,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-
-c_constructor = rffi.llexternal(
-    "cppyy_constructor",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP], lltype.Void,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-_c_call_o = rffi.llexternal(
-    "cppyy_call_o",
-    [C_METHOD, C_OBJECT, rffi.INT, rffi.VOIDP, C_TYPE], rffi.LONG,
-    threadsafe=ts_call,
-    compilation_info=backend.eci)
-def c_call_o(method, cppobj, nargs, args, cppclass):
-    return _c_call_o(method, cppobj, nargs, args, cppclass.handle)
-
-_c_get_methptr_getter = rffi.llexternal(
-    "cppyy_get_methptr_getter",
-    [C_SCOPE, C_INDEX], C_METHPTRGETTER_PTR,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci,
-    elidable_function=True)
-def c_get_methptr_getter(cppscope, index):
-    return _c_get_methptr_getter(cppscope.handle, index)
-
-# handling of function argument buffer ---------------------------------------
-c_allocate_function_args = rffi.llexternal(
-    "cppyy_allocate_function_args",
-    [rffi.SIZE_T], rffi.VOIDP,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci)
-c_deallocate_function_args = rffi.llexternal(
-    "cppyy_deallocate_function_args",
-    [rffi.VOIDP], lltype.Void,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci)
-c_function_arg_sizeof = rffi.llexternal(
-    "cppyy_function_arg_sizeof",
-    [], rffi.SIZE_T,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci,
-    elidable_function=True)
-c_function_arg_typeoffset = rffi.llexternal(
-    "cppyy_function_arg_typeoffset",
-    [], rffi.SIZE_T,
-    threadsafe=ts_memory,
-    compilation_info=backend.eci,
-    elidable_function=True)
-
-# scope reflection information -----------------------------------------------
-c_is_namespace = rffi.llexternal(
-    "cppyy_is_namespace",
-    [C_SCOPE], rffi.INT,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-c_is_enum = rffi.llexternal(
-    "cppyy_is_enum",
-    [rffi.CCHARP], rffi.INT,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-
-# type/class reflection information ------------------------------------------
-_c_final_name = rffi.llexternal(
-    "cppyy_final_name",
-    [C_TYPE], rffi.CCHARP,
-    threadsafe=ts_reflect,
-    compilation_info=backend.eci)
-def c_final_name(cpptype):
-    return charp2str_free(_c_final_name(cpptype))
-_c_scoped_final_name = rffi.llexternal(
-    "cppyy_scoped_final_name",
-    [C_TYPE], rffi.CCHARP,
-    threadsafe=ts_reflect,