1. Pypy
  2. Untitled project
  3. pypy

Commits

Maciej Fijalkowski  committed 0155f66 Merge

merge default (I hope)

  • Participants
  • Parent commits 2e85224, d8124d5
  • Branches kill-gen-store-back-in

Comments (0)

Files changed (81)

File dotviewer/drawgraph.py

View file
  • Ignore whitespace
     'yellow': (255,255,0),
     }
 re_nonword=re.compile(r'([^0-9a-zA-Z_.]+)')
+re_linewidth=re.compile(r'setlinewidth\((\d+(\.\d*)?|\.\d+)\)')
 
 def combine(color1, color2, alpha):
     r1, g1, b1 = color1
             self.yl = float(yl)
             rest = rest[3:]
         self.style, self.color = rest
+        linematch = re_linewidth.match(self.style)
+        if linematch:
+            num = linematch.group(1)
+            self.linewidth = int(round(float(num)))
+            self.style = self.style[linematch.end(0):]
+        else:
+            self.linewidth = 1
         self.highlight = False
         self.cachedbezierpoints = None
         self.cachedarrowhead = None
                 fgcolor = highlight_color(fgcolor)
             points = [self.map(*xy) for xy in edge.bezierpoints()]
 
-            def drawedgebody(points=points, fgcolor=fgcolor):
-                pygame.draw.lines(self.screen, fgcolor, False, points)
+            def drawedgebody(points=points, fgcolor=fgcolor, width=edge.linewidth):
+                pygame.draw.lines(self.screen, fgcolor, False, points, width)
             edgebodycmd.append(drawedgebody)
 
             points = [self.map(*xy) for xy in edge.arrowhead()]

File dotviewer/test/test_interactive.py

View file
  • Ignore whitespace
 }
 '''
 
+SOURCE2=r'''digraph f {
+  a; d; e; f; g; h; i; j; k; l;
+  a -> d [penwidth=1, style="setlinewidth(1)"];
+  d -> e [penwidth=2, style="setlinewidth(2)"];
+  e -> f [penwidth=4, style="setlinewidth(4)"];
+  f -> g [penwidth=8, style="setlinewidth(8)"];
+  g -> h [penwidth=16, style="setlinewidth(16)"];
+  h -> i [penwidth=32, style="setlinewidth(32)"];
+  i -> j [penwidth=64, style="setlinewidth(64)"];
+  j -> k [penwidth=128, style="setlinewidth(128)"];
+  k -> l [penwidth=256, style="setlinewidth(256)"];
+}'''
+
+
+
+
+
 def setup_module(mod):
     if not option.pygame:
         py.test.skip("--pygame not enabled")
     page = MyPage(str(dotfile))
     page.fixedfont = True
     graphclient.display_page(page)
+
+def test_linewidth():
+    udir.join("graph2.dot").write(SOURCE2)
+    from dotviewer import graphpage, graphclient
+    dotfile = udir.join('graph2.dot')
+    page = graphpage.DotFileGraphPage(str(dotfile))
+    graphclient.display_page(page)

File lib-python/2.7/ssl.py

View file
  • Ignore whitespace
                  suppress_ragged_eofs=True, ciphers=None):
         socket.__init__(self, _sock=sock._sock)
 
+        # "close" the original socket: it is not usable any more.
+        # this only calls _drop(), which should not actually call
+        # the operating system's close() because the reference
+        # counter is greater than 1 (we hold one too).
+        sock.close()
+
         if ciphers is None and ssl_version != _SSLv2_IF_EXISTS:
             ciphers = _DEFAULT_CIPHERS
 

File lib_pypy/_sqlite3.py

View file
  • Ignore whitespace
         for i in xrange(_lib.sqlite3_column_count(self._statement)):
             name = _lib.sqlite3_column_name(self._statement, i)
             if name:
-                name = _ffi.string(name).decode('utf-8').split("[")[0].strip()
+                name = _ffi.string(name).split("[")[0].strip()
             desc.append((name, None, None, None, None, None, None))
         return desc
 

File pypy/doc/_ref.txt

View file
  • Ignore whitespace
 .. _`rpython/rtyper/memory/gc/hybrid.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/memory/gc/hybrid.py
 .. _`rpython/rtyper/memory/gc/minimarkpage.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/memory/gc/minimarkpage.py
 .. _`rpython/rtyper/memory/gc/semispace.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/memory/gc/semispace.py
-.. _`rpython/rtyper/ootypesystem/`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/ootypesystem/
-.. _`rpython/rtyper/ootypesystem/ootype.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/ootypesystem/ootype.py
 .. _`rpython/rtyper/rint.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/rint.py
 .. _`rpython/rtyper/rlist.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/rlist.py
 .. _`rpython/rtyper/rmodel.py`: https://bitbucket.org/pypy/pypy/src/default/rpython/rtyper/rmodel.py

File pypy/doc/whatsnew-head.rst

View file
  • Ignore whitespace
 .. branch: foldable-getarrayitem-indexerror
 Constant-fold reading out of constant tuples in PyPy.
 
+.. branch: mro-reorder-numpypy-str
+No longer delegate numpy string_ methods to space.StringObject, in numpy
+this works by kind of by accident. Support for merging the refactor-str-types
+branch
+
+.. branch: kill-typesystem
+Remove the "type system" abstraction, now that there is only ever one kind of
+type system used.

File pypy/module/cppyy/interp_cppyy.py

View file
  • Ignore whitespace
 
     def get(self, w_cppinstance, w_pycppclass):
         cppinstance = self.space.interp_w(W_CPPInstance, w_cppinstance, can_be_None=True)
+        if not cppinstance:
+            raise OperationError(self.space.w_ReferenceError, self.space.wrap("attribute access requires an instance")) 
         offset = self._get_offset(cppinstance)
         return self.converter.from_memory(self.space, w_cppinstance, w_pycppclass, offset)
 
     def set(self, w_cppinstance, w_value):
         cppinstance = self.space.interp_w(W_CPPInstance, w_cppinstance, can_be_None=True)
+        if not cppinstance:
+            raise OperationError(self.space.w_ReferenceError, self.space.wrap("attribute access requires an instance"))
         offset = self._get_offset(cppinstance)
         self.converter.to_memory(self.space, w_cppinstance, w_value, offset)
         return self.space.w_None

File pypy/module/cppyy/pythonify.py

View file
  • Ignore whitespace
     # mostly for the benefit of the CINT backend, which treats std as special
     gbl.std = make_cppnamespace(None, "std", None, False)
 
+    # install a type for enums to refer to
+    # TODO: this is correct for C++98, not for C++11 and in general there will
+    # be the same issue for all typedef'd builtin types
+    setattr(gbl, 'unsigned int', int)
+
     # install for user access
     cppyy.gbl = gbl
 

File pypy/module/cppyy/test/test_datatypes.py

View file
  • Ignore whitespace
         raises(IndexError, c.m_float_array.__getitem__,  self.N)
         raises(IndexError, c.m_double_array.__getitem__, self.N)
 
+        # can not access an instance member on the class
+        raises(ReferenceError, getattr, cppyy_test_data, 'm_bool')
+        raises(ReferenceError, getattr, cppyy_test_data, 'm_int')
+
+        assert not hasattr(cppyy_test_data, 'm_bool')
+        assert not hasattr(cppyy_test_data, 'm_int')
+
         c.destruct()
 
     def test03_instance_data_write_access(self):
         c = cppyy_test_data()
         assert isinstance(c, cppyy_test_data)
 
-        # TODO: test that the enum is accessible as a type
+        # test that the enum is accessible as a type
+        assert cppyy_test_data.what
 
         assert cppyy_test_data.kNothing   ==   6
         assert cppyy_test_data.kSomething == 111
         assert cppyy_test_data.kLots      ==  42
 
+        assert cppyy_test_data.what(cppyy_test_data.kNothing) == cppyy_test_data.kNothing
+        assert cppyy_test_data.what(6) == cppyy_test_data.kNothing
+        # TODO: only allow instantiations with correct values (C++11)
+
         assert c.get_enum() == cppyy_test_data.kNothing
         assert c.m_enum == cppyy_test_data.kNothing
 
         assert cppyy_test_data.s_enum == cppyy_test_data.kSomething
 
         # global enums
+        assert gbl.fruit          # test type accessible
         assert gbl.kApple  == 78
         assert gbl.kBanana == 29
         assert gbl.kCitrus == 34

File pypy/module/micronumpy/interp_boxes.py

View file
  • Ignore whitespace
         return self
 
 class W_CharacterBox(W_FlexibleBox):
-    pass
+    def convert_to(self, dtype):
+        # XXX assert dtype is str type
+        return self
+
 
 class W_StringBox(W_CharacterBox):
     def descr__new__string_box(space, w_subtype, w_arg):
         from pypy.module.micronumpy.interp_dtype import new_string_dtype
-
         arg = space.str_w(space.str(w_arg))
         arr = VoidBoxStorage(len(arg), new_string_dtype(space, len(arg)))
         for i in range(len(arg)):
     __module__ = "numpypy",
 )
 
-W_StringBox.typedef = TypeDef("string_", (str_typedef, W_CharacterBox.typedef),
+W_StringBox.typedef = TypeDef("string_", (W_CharacterBox.typedef, str_typedef),
     __module__ = "numpypy",
     __new__ = interp2app(W_StringBox.descr__new__string_box.im_func),
 )
 
-W_UnicodeBox.typedef = TypeDef("unicode_", (unicode_typedef, W_CharacterBox.typedef),
+W_UnicodeBox.typedef = TypeDef("unicode_", (W_CharacterBox.typedef, unicode_typedef),
     __module__ = "numpypy",
     __new__ = interp2app(W_UnicodeBox.descr__new__unicode_box.im_func),
 )

File pypy/module/micronumpy/interp_dtype.py

View file
  • Ignore whitespace
     def is_record_type(self):
         return self.fields is not None
 
+    def is_str_type(self):
+        return self.num == 18
+
     def is_str_or_unicode(self):
         return (self.num == 18 or self.num == 19)
 

File pypy/module/micronumpy/interp_ufuncs.py

View file
  • Ignore whitespace
             w_out = None
         w_lhs = convert_to_array(space, w_lhs)
         w_rhs = convert_to_array(space, w_rhs)
-        if (w_lhs.get_dtype().is_flexible_type() or \
-                w_rhs.get_dtype().is_flexible_type()):
+        w_ldtype = w_lhs.get_dtype()
+        w_rdtype = w_rhs.get_dtype()
+        if w_ldtype.is_str_type() and w_rdtype.is_str_type() and \
+           self.comparison_func:
+            pass
+        elif (w_ldtype.is_flexible_type() or \
+                w_rdtype.is_flexible_type()):
             raise OperationError(space.w_TypeError, space.wrap(
                  'unsupported operand dtypes %s and %s for "%s"' % \
-                 (w_rhs.get_dtype().get_name(), w_lhs.get_dtype().get_name(),
+                 (w_rdtype.get_name(), w_ldtype.get_name(),
                   self.name)))
         calc_dtype = find_binop_result_dtype(space,
-            w_lhs.get_dtype(), w_rhs.get_dtype(),
+            w_ldtype, w_rdtype,
             int_only=self.int_only,
             promote_to_float=self.promote_to_float,
             promote_bools=self.promote_bools,

File pypy/module/micronumpy/stdobjspace.py

  • Ignore whitespace
-
-from pypy.objspace.std import stringobject
-from pypy.module.micronumpy import interp_boxes
-
-def delegate_stringbox2stringobj(space, w_box):
-    return space.wrap(w_box.dtype.itemtype.to_str(w_box))
-
-def register_delegates(typeorder):
-    typeorder[interp_boxes.W_StringBox] = [
-        (stringobject.W_StringObject, delegate_stringbox2stringobj),
-    ]

File pypy/module/micronumpy/test/test_dtypes.py

View file
  • Ignore whitespace
 
 class AppTestStrUnicodeDtypes(BaseNumpyAppTest):
     def test_str_unicode(self):
+        skip('numpypy differs from numpy')
         from numpypy import str_, unicode_, character, flexible, generic
 
         assert str_.mro() == [str_, str, basestring, character, flexible, generic, object]

File pypy/module/micronumpy/test/test_numarray.py

View file
  • Ignore whitespace
         assert a[2] == 'ab'
         raises(TypeError, a, 'sum')
         raises(TypeError, 'a+a')
+        b = array(['abcdefg', 'ab', 'cd'])
+        assert a[2] == b[1]
+        assert bool(a[1])
+        c = array(['ab','cdefg','hi','jk'])
+        # not implemented yet
+        #c[0] += c[3]
+        #assert c[0] == 'abjk'
+
+    def test_to_str(self):
+        from numpypy import array
+        a = array(['abc','abc', 'def', 'ab'], 'S3')
+        b = array(['mnopqr','abcdef', 'ab', 'cd'])
+        assert b[1] != a[1]
 
     def test_string_scalar(self):
         from numpypy import array
         assert str(a.dtype) == '|S1'
         a = array('x', dtype='c')
         assert str(a.dtype) == '|S1'
-        # XXX can sort flexible types, why not comparison?
-        #assert a == 'x'
+        assert a == 'x'
 
     def test_flexible_repr(self):
         from numpypy import array

File pypy/module/micronumpy/types.py

View file
  • Ignore whitespace
     def get_size(self):
         return self.size
 
+def str_unary_op(func):
+    specialize.argtype(1)(func)
+    @functools.wraps(func)
+    def dispatcher(self, v1):
+        return func(self, self.to_str(v1))
+    return dispatcher
+
+def str_binary_op(func):
+    specialize.argtype(1, 2)(func)
+    @functools.wraps(func)
+    def dispatcher(self, v1, v2):
+        return func(self,
+            self.to_str(v1),
+            self.to_str(v2)
+        )
+    return dispatcher
 
 class StringType(BaseType, BaseStringType):
     T = lltype.Char
     @jit.unroll_safe
     def coerce(self, space, dtype, w_item):
         from pypy.module.micronumpy.interp_dtype import new_string_dtype
+        if isinstance(w_item, interp_boxes.W_StringBox):
+            return w_item
         arg = space.str_w(space.str(w_item))
         arr = VoidBoxStorage(len(arg), new_string_dtype(space, len(arg)))
         for i in range(len(arg)):
     @jit.unroll_safe
     def store(self, arr, i, offset, box):
         assert isinstance(box, interp_boxes.W_StringBox)
+        # XXX simplify to range(box.dtype.get_size()) ?
         for k in range(min(self.size, box.arr.size-offset)):
             arr.storage[k + i] = box.arr.storage[k + offset]
 
         builder = StringBuilder()
         assert isinstance(item, interp_boxes.W_StringBox)
         i = item.ofs
-        end = i+self.size
+        end = i + item.dtype.get_size()
         while i < end:
             assert isinstance(item.arr.storage[i], str)
             if item.arr.storage[i] == '\x00':
         builder.append("'")
         return builder.build()
 
-    # XXX move to base class when UnicodeType is supported
+    # XXX move the rest of this to base class when UnicodeType is supported
     def to_builtin_type(self, space, box):
         return space.wrap(self.to_str(box))
 
+    @str_binary_op
+    def eq(self, v1, v2):
+        return v1 == v2
+
+    @str_binary_op
+    def ne(self, v1, v2):
+        return v1 != v2
+
+    @str_binary_op
+    def lt(self, v1, v2):
+        return v1 < v2
+
+    @str_binary_op
+    def le(self, v1, v2):
+        return v1 <= v2
+
+    @str_binary_op
+    def gt(self, v1, v2):
+        return v1 > v2
+
+    @str_binary_op
+    def ge(self, v1, v2):
+        return v1 >= v2
+
+    @str_binary_op
+    def logical_and(self, v1, v2):
+        return bool(v1) and bool(v2)
+
+    @str_binary_op
+    def logical_or(self, v1, v2):
+        return bool(v1) or bool(v2)
+
+    @str_unary_op
+    def logical_not(self, v):
+        return not bool(v)
+
+    @str_binary_op
+    def logical_xor(self, v1, v2):
+        return bool(v1) ^ bool(v2)
+
+    def bool(self, v):
+        return bool(self.to_str(v))
+
     def build_and_convert(self, space, mydtype, box):
         assert isinstance(box, interp_boxes.W_GenericBox)
         if box.get_dtype(space).is_str_or_unicode():
             arr.storage[j] = '\x00'
         return interp_boxes.W_StringBox(arr,  0, arr.dtype)
 
+NonNativeStringType = StringType
+
+class UnicodeType(BaseType, BaseStringType):
+    T = lltype.UniChar
+
+NonNativeUnicodeType = UnicodeType
+
 class VoidType(BaseType, BaseStringType):
     T = lltype.Char
 
         return W_NDimArray(implementation)
 
 NonNativeVoidType = VoidType
-NonNativeStringType = StringType
-
-class UnicodeType(BaseType, BaseStringType):
-    T = lltype.UniChar
-
-NonNativeUnicodeType = UnicodeType
 
 class RecordType(BaseType):
 

File pypy/module/test_lib_pypy/test_sqlite3.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
 """Tests for _sqlite3.py"""
 
 import pytest, sys
     cur.execute("create table test(a)")
     cur.executemany("insert into test values (?)", [[1], [2], [3]])
     assert cur.lastrowid is None
+
+def test_issue1573(con):
+    cur = con.cursor()
+    cur.execute(u'SELECT 1 as méil')
+    assert cur.description[0][0] == u"méil".encode('utf-8')

File pypy/objspace/std/model.py

View file
  • Ignore whitespace
         # when trying to dispatch multimethods.
         # XXX build these lists a bit more automatically later
 
-        if config.objspace.usemodules.micronumpy:
-            from pypy.module.micronumpy.stdobjspace import register_delegates
-            register_delegates(self.typeorder)
-
         self.typeorder[boolobject.W_BoolObject] += [
             (intobject.W_IntObject,     boolobject.delegate_Bool2IntObject),
             (floatobject.W_FloatObject, floatobject.delegate_Bool2Float),

File pypy/tool/release/package.py

View file
  • Ignore whitespace
 It uses 'pypy/goal/pypy-c' and parts of the rest of the working
 copy.  Usage:
 
-    package.py root-pypy-dir [--nostrip] [--without-tk] [name-of-archive] [name-of-pypy-c] [destination-for-tarball] [pypy-c-path]
+    package.py [--nostrip] [--without-tk] root-pypy-dir [name-of-archive] [name-of-pypy-c] [destination-for-tarball] [pypy-c-path]
 
 Usually you would do:   package.py ../../.. pypy-VER-PLATFORM
 The output is found in the directory /tmp/usession-YOURNAME/build/.

File rpython/jit/backend/test/support.py

View file
  • Ignore whitespace
 
         t.buildannotator().build_types(function, [int] * len(args),
                                        main_entry_point=True)
-        t.buildrtyper(type_system=self.type_system).specialize()
+        t.buildrtyper().specialize()
         warmrunnerdesc = WarmRunnerDesc(t, translate_support_code=True,
                                         CPUClass=self.CPUClass,
                                         **kwds)

File rpython/jit/codewriter/codewriter.py

View file
  • Ignore whitespace
         self.callcontrol = CallControl(cpu, jitdrivers_sd)
         self._seen_files = set()
 
-    def transform_func_to_jitcode(self, func, values, type_system='lltype'):
+    def transform_func_to_jitcode(self, func, values):
         """For testing."""
-        rtyper = support.annotate(func, values, type_system=type_system)
+        rtyper = support.annotate(func, values)
         graph = rtyper.annotator.translator.graphs[0]
         jitcode = JitCode("test")
         self.transform_graph_to_jitcode(graph, jitcode, True)

File rpython/jit/codewriter/support.py

View file
  • Ignore whitespace
     return a.typeannotation(t)
 
 def annotate(func, values, inline=None, backendoptimize=True,
-             type_system="lltype", translationoptions={}):
+             translationoptions={}):
     # build the normal ll graphs for ll_function
     t = TranslationContext()
     for key, value in translationoptions.items():
     a = t.buildannotator(policy=annpolicy)
     argtypes = getargtypes(a, values)
     a.build_types(func, argtypes, main_entry_point=True)
-    rtyper = t.buildrtyper(type_system = type_system)
+    rtyper = t.buildrtyper()
     rtyper.specialize()
     #if inline:
     #    auto_inlining(t, threshold=inline)

File rpython/jit/codewriter/test/test_flatten.py

View file
  • Ignore whitespace
 
 class TestFlatten:
 
-    def make_graphs(self, func, values, type_system='lltype'):
-        self.rtyper = support.annotate(func, values, type_system=type_system)
+    def make_graphs(self, func, values):
+        self.rtyper = support.annotate(func, values)
         return self.rtyper.annotator.translator.graphs
 
     def encoding_test(self, func, args, expected,

File rpython/jit/codewriter/test/test_regalloc.py

View file
  • Ignore whitespace
 
 class TestRegAlloc:
 
-    def make_graphs(self, func, values, type_system='lltype'):
-        self.rtyper = support.annotate(func, values, type_system=type_system)
+    def make_graphs(self, func, values):
+        self.rtyper = support.annotate(func, values)
         return self.rtyper.annotator.translator.graphs
 
     def check_assembler(self, graph, expected, transform=False,

File rpython/jit/metainterp/jitexc.py

View file
  • Ignore whitespace
 
 
 def _get_standard_error(rtyper, Class):
-    exdata = rtyper.getexceptiondata()
+    exdata = rtyper.exceptiondata
     clsdef = rtyper.annotator.bookkeeper.getuniqueclassdef(Class)
     evalue = exdata.get_standard_ll_exc_instance(rtyper, clsdef)
     return evalue

File rpython/jit/metainterp/test/support.py

View file
  • Ignore whitespace
 from rpython.translator.backendopt.all import backend_optimizations
 
 
-def _get_jitcodes(testself, CPUClass, func, values, type_system,
+def _get_jitcodes(testself, CPUClass, func, values,
                   supports_floats=True,
                   supports_longlong=False,
                   supports_singlefloats=False,
         FakeWarmRunnerState.enable_opts = {}
 
     func._jit_unroll_safe_ = True
-    rtyper = support.annotate(func, values, type_system=type_system,
+    rtyper = support.annotate(func, values,
                               translationoptions=translationoptions)
     graphs = rtyper.annotator.translator.graphs
     testself.all_graphs = graphs
 
     def interp_operations(self, f, args, **kwds):
         # get the JitCodes for the function f
-        _get_jitcodes(self, self.CPUClass, f, args, self.type_system, **kwds)
+        _get_jitcodes(self, self.CPUClass, f, args, **kwds)
         # try to run it with blackhole.py
         result1 = _run_with_blackhole(self, args)
         # try to run it with pyjitpl.py

File rpython/jit/metainterp/test/test_virtualizable.py

View file
  • Ignore whitespace
                                        if getattr(graph, 'func', None) is f]
         init_graph = t._graphof(Frame.__init__.im_func)
 
-        deref = t.rtyper.type_system_deref
+        deref = t.rtyper.type_system.deref
 
         def direct_calls(graph):
             return [deref(op.args[0].value)._callable.func_name

File rpython/jit/metainterp/test/test_virtualref.py

View file
  • Ignore whitespace
             x1 = vref()                  # jit_force_virtual
             virtual_ref_finish(vref, x)
         #
-        _get_jitcodes(self, self.CPUClass, fn, [], self.type_system)
+        _get_jitcodes(self, self.CPUClass, fn, [])
         graph = self.all_graphs[0]
         assert graph.name == 'fn'
         self.vrefinfo.replace_force_virtual_with_call([graph])

File rpython/memory/gctransform/transform.py

View file
  • Ignore whitespace
             self.minimalgctransformer = None
 
     def get_lltype_of_exception_value(self):
-        exceptiondata = self.translator.rtyper.getexceptiondata()
+        exceptiondata = self.translator.rtyper.exceptiondata
         return exceptiondata.lltype_of_exception_value
 
     def need_minimal_transform(self, graph):
         flags = hop.spaceop.args[1].value
         flavor = flags['flavor']
         meth = getattr(self, 'gct_fv_%s_malloc' % flavor, None)
-        assert meth, "%s has no support for malloc with flavor %r" % (self, flavor) 
+        assert meth, "%s has no support for malloc with flavor %r" % (self, flavor)
         c_size = rmodel.inputconst(lltype.Signed, llmemory.sizeof(TYPE))
         v_raw = meth(hop, flags, TYPE, c_size)
         hop.cast_result(v_raw)
- 
+
     def gct_fv_raw_malloc(self, hop, flags, TYPE, c_size):
         v_raw = hop.genop("direct_call", [self.raw_malloc_fixedsize_ptr, c_size],
                           resulttype=llmemory.Address)
             flags.update(add_flags)
         flavor = flags['flavor']
         meth = getattr(self, 'gct_fv_%s_malloc_varsize' % flavor, None)
-        assert meth, "%s has no support for malloc_varsize with flavor %r" % (self, flavor) 
+        assert meth, "%s has no support for malloc_varsize with flavor %r" % (self, flavor)
         return self.varsize_malloc_helper(hop, flags, meth, [])
 
     def gct_malloc_nonmovable(self, *args, **kwds):

File rpython/rlib/debug.py

View file
  • Ignore whitespace
         return None
 
     def specialize_call(self, hop):
+        from rpython.rtyper.lltypesystem.rstr import string_repr
         fn = self.instance
-        string_repr = hop.rtyper.type_system.rstr.string_repr
         vlist = hop.inputargs(string_repr)
         hop.exception_cannot_occur()
         t = hop.rtyper.annotator.translator
 
     def compute_result_annotation(self):
         return None
-    
+
     def specialize_call(self, hop):
         hop.exception_cannot_occur()
         return hop.genop('debug_flush', [])
             from rpython.annotator.annrpython import log
             log.WARNING('make_sure_not_resized called, but has no effect since list_comprehension is off')
         return s_arg
-    
+
     def specialize_call(self, hop):
         hop.exception_cannot_occur()
         return hop.inputarg(hop.args_r[0], arg=0)
 
 class DictMarkEntry(ExtRegistryEntry):
     _about_ = mark_dict_non_null
-    
+
     def compute_result_annotation(self, s_dict):
         from rpython.annotator.model import SomeDict
 

File rpython/rlib/rstring.py

View file
  • Ignore whitespace
         return SomeString()
 
     def rtyper_makerepr(self, rtyper):
-        return rtyper.type_system.rbuilder.stringbuilder_repr
+        from rpython.rtyper.lltypesystem.rbuilder import stringbuilder_repr
+        return stringbuilder_repr
 
     def rtyper_makekey(self):
         return self.__class__,
         return SomeUnicodeString()
 
     def rtyper_makerepr(self, rtyper):
-        return rtyper.type_system.rbuilder.unicodebuilder_repr
+        from rpython.rtyper.lltypesystem.rbuilder import unicodebuilder_repr
+        return unicodebuilder_repr
 
     def rtyper_makekey(self):
         return self.__class__,

File rpython/rtyper/annlowlevel.py

View file
  • Ignore whitespace
 from rpython.annotator.policy import AnnotatorPolicy
 from rpython.annotator.signature import Sig
 from rpython.annotator.specialize import flatten_star_args
+from rpython.rtyper.normalizecalls import perform_normalizations
 from rpython.rtyper.lltypesystem import lltype, llmemory
 from rpython.flowspace.model import Constant
 from rpython.rlib.objectmodel import specialize
         return LowLevelAnnotatorPolicy.lowlevelspecialize(funcdesc, args_s, {})
     default_specialize = staticmethod(default_specialize)
 
-    def specialize__ts(pol, funcdesc, args_s, ref):
-        ts = pol.rtyper.type_system
-        ref = ref.split('.')
-        x = ts
-        for part in ref:
-            x = getattr(x, part)
-        bk = pol.rtyper.annotator.bookkeeper
-        funcdesc2 = bk.getdesc(x)
-        return pol.default_specialize(funcdesc2, args_s)
-
     def specialize__semierased(funcdesc, args_s):
         a2l = annmodel.annotation_to_lltype
         l2a = annmodel.lltype_to_annotation
         rtyper = self.rtyper
         translator = rtyper.annotator.translator
         original_graph_count = len(translator.graphs)
-        rtyper.type_system.perform_normalizations(rtyper)
+        perform_normalizations(rtyper)
         for r in self.delayedreprs:
             r.set_setup_delayed(False)
         rtyper.call_all_setups()

File rpython/rtyper/callparse.py

View file
  • Ignore whitespace
         return self.holders
 
     def _emit(self, repr, hop):
-        assert isinstance(repr, rtuple.AbstractTupleRepr)
+        assert isinstance(repr, rtuple.TupleRepr)
         tupleitems_v = []
         for h in self.holders:
             v = h.emit(repr.items_r[len(tupleitems_v)], hop)

File rpython/rtyper/exceptiondata.py

View file
  • Ignore whitespace
 from rpython.annotator import model as annmodel
 from rpython.rlib import rstackovf
 from rpython.rtyper import rclass
-
+from rpython.rtyper.lltypesystem.rclass import (ll_issubclass, ll_type,
+        ll_cast_to_object)
 
 # the exceptions that can be implicitely raised by some operations
-standardexceptions = {
-    TypeError        : True,
-    OverflowError    : True,
-    ValueError       : True,
-    ZeroDivisionError: True,
-    MemoryError      : True,
-    IOError          : True,
-    OSError          : True,
-    StopIteration    : True,
-    KeyError         : True,
-    IndexError       : True,
-    AssertionError   : True,
-    RuntimeError     : True,
-    UnicodeDecodeError: True,
-    UnicodeEncodeError: True,
-    NotImplementedError: True,
-    rstackovf._StackOverflow: True,
-    }
+standardexceptions = set([TypeError, OverflowError, ValueError,
+    ZeroDivisionError, MemoryError, IOError, OSError, StopIteration, KeyError,
+    IndexError, AssertionError, RuntimeError, UnicodeDecodeError,
+    UnicodeEncodeError, NotImplementedError, rstackovf._StackOverflow])
 
 class UnknownException(Exception):
     pass
 
 
-class AbstractExceptionData:
+class ExceptionData(object):
     """Public information for the code generators to help with exceptions."""
+
     standardexceptions = standardexceptions
 
     def __init__(self, rtyper):
         return helper_fn
 
     def get_standard_ll_exc_instance(self, rtyper, clsdef):
-        rclass = rtyper.type_system.rclass
-        r_inst = rclass.getinstancerepr(rtyper, clsdef)
+        from rpython.rtyper.lltypesystem.rclass import getinstancerepr
+        r_inst = getinstancerepr(rtyper, clsdef)
         example = r_inst.get_reusable_prebuilt_instance()
-        example = self.cast_exception(self.lltype_of_exception_value, example)
+        example = ll_cast_to_object(example)
         return example
 
     def get_standard_ll_exc_instance_by_class(self, exceptionclass):
         clsdef = self.rtyper.annotator.bookkeeper.getuniqueclassdef(
             exceptionclass)
         return self.get_standard_ll_exc_instance(self.rtyper, clsdef)
+
+    def make_helpers(self, rtyper):
+        # create helper functionptrs
+        self.fn_exception_match  = self.make_exception_matcher(rtyper)
+        self.fn_type_of_exc_inst = self.make_type_of_exc_inst(rtyper)
+        self.fn_raise_OSError    = self.make_raise_OSError(rtyper)
+
+    def make_exception_matcher(self, rtyper):
+        # ll_exception_matcher(real_exception_vtable, match_exception_vtable)
+        s_typeptr = annmodel.SomePtr(self.lltype_of_exception_type)
+        helper_fn = rtyper.annotate_helper_fn(ll_issubclass, [s_typeptr, s_typeptr])
+        return helper_fn
+
+    def make_type_of_exc_inst(self, rtyper):
+        # ll_type_of_exc_inst(exception_instance) -> exception_vtable
+        s_excinst = annmodel.SomePtr(self.lltype_of_exception_value)
+        helper_fn = rtyper.annotate_helper_fn(ll_type, [s_excinst])
+        return helper_fn

File rpython/rtyper/extfuncregistry.py

View file
  • Ignore whitespace
                           sandboxsafe=True,
                           llimpl=getattr(ll_math, method_name))
 
-# ___________________________
-# os.path functions
-
-from rpython.tool.sourcetools import func_with_new_name
-import os.path
-
-# os.path.join is RPython, but we don't want to compile it directly
-# because it's platform dependant. This is ok for lltype where the
-# execution platform is the same as the translation platform, but not
-# for ootype where the executable produced by some backends (e.g. CLI,
-# JVM) are expected to run everywhere.  Thus, we register it as an
-# external function, but we provide a clone for lltype using
-# func_with_new_name.
-
-path_functions = [
-    ('join',     [ll_os.str0, ll_os.str0], ll_os.str0),
-    ('dirname',  [ll_os.str0], ll_os.str0),
-    ]
-
-for name, args, res in path_functions:
-    func = getattr(os.path, name)
-    llimpl = func_with_new_name(func, name)
-    register_external(func, args, res, 'll_os_path.ll_%s' % name,
-                      llimpl=llimpl, sandboxsafe=True)

File rpython/rtyper/llinterp.py

View file
  • Ignore whitespace
             rtyper = self.llinterpreter.typer
             bk = rtyper.annotator.bookkeeper
             classdef = bk.getuniqueclassdef(rstackovf._StackOverflow)
-            exdata = rtyper.getexceptiondata()
+            exdata = rtyper.exceptiondata
             evalue = exdata.get_standard_ll_exc_instance(rtyper, classdef)
             etype = exdata.fn_type_of_exc_inst(evalue)
             e = LLException(etype, evalue)
         elif catch_exception:
             link = block.exits[0]
             if e:
-                exdata = self.llinterpreter.typer.getexceptiondata()
+                exdata = self.llinterpreter.typer.exceptiondata
                 cls = e.args[0]
                 inst = e.args[1]
                 for link in block.exits[1:]:
         else:
             extraargs = ()
         typer = self.llinterpreter.typer
-        exdata = typer.getexceptiondata()
+        exdata = typer.exceptiondata
         if isinstance(exc, OSError):
             self.op_direct_call(exdata.fn_raise_OSError, exc.errno)
             assert False, "op_direct_call above should have raised"

File rpython/rtyper/lltypesystem/exceptiondata.py

  • Ignore whitespace
-from rpython.annotator import model as annmodel
-from rpython.rtyper.lltypesystem import rclass
-from rpython.rtyper.lltypesystem.lltype import (Array, malloc, Ptr, FuncType,
-    functionptr, Signed)
-from rpython.rtyper.exceptiondata import AbstractExceptionData
-from rpython.annotator.classdef import FORCE_ATTRIBUTES_INTO_CLASSES
-
-
-class ExceptionData(AbstractExceptionData):
-    """Public information for the code generators to help with exceptions."""
-
-    def make_helpers(self, rtyper):
-        # create helper functionptrs
-        self.fn_exception_match  = self.make_exception_matcher(rtyper)
-        self.fn_type_of_exc_inst = self.make_type_of_exc_inst(rtyper)
-        self.fn_raise_OSError    = self.make_raise_OSError(rtyper)
-
-    def make_exception_matcher(self, rtyper):
-        # ll_exception_matcher(real_exception_vtable, match_exception_vtable)
-        s_typeptr = annmodel.SomePtr(self.lltype_of_exception_type)
-        helper_fn = rtyper.annotate_helper_fn(rclass.ll_issubclass, [s_typeptr, s_typeptr])
-        return helper_fn
-
-    def make_type_of_exc_inst(self, rtyper):
-        # ll_type_of_exc_inst(exception_instance) -> exception_vtable
-        s_excinst = annmodel.SomePtr(self.lltype_of_exception_value)
-        helper_fn = rtyper.annotate_helper_fn(rclass.ll_type, [s_excinst])
-        return helper_fn
-
-    def cast_exception(self, TYPE, value):
-        return rclass.ll_cast_to_object(value)

File rpython/rtyper/lltypesystem/ll_str.py

View file
  • Ignore whitespace
 from rpython.rtyper.lltypesystem.lltype import GcArray, Array, Char, malloc
-from rpython.rtyper.annlowlevel import llstr
 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
 from rpython.rlib import jit
 
 CHAR_ARRAY = GcArray(Char)
 
-@jit.elidable
-def ll_int_str(repr, i):
-    return ll_int2dec(i)
-
 def ll_unsigned(i):
     if isinstance(i, r_longlong) or isinstance(i, r_ulonglong):
         return r_ulonglong(i)
 hex_chars = malloc(Array(Char), 16, immortal=True)
 
 for i in range(16):
-    hex_chars[i] = "%x"%i
+    hex_chars[i] = "%x" % i
 
 @jit.elidable
 def ll_int2hex(i, addPrefix):
         result.chars[j] = temp[len-j-1]
         j += 1
     return result
-
-@jit.elidable
-def ll_float_str(repr, f):
-    from rpython.rlib.rfloat import formatd
-    return llstr(formatd(f, 'f', 6))

File rpython/rtyper/lltypesystem/rbuiltin.py

  • Ignore whitespace
-from rpython.annotator import model as annmodel
-from rpython.rlib import objectmodel
-from rpython.rtyper.lltypesystem import lltype, rclass
-from rpython.rtyper.lltypesystem.rdict import rtype_r_dict
-from rpython.rtyper.rmodel import TyperError
-
-
-def rtype_builtin_isinstance(hop):
-    hop.exception_cannot_occur()
-    if hop.s_result.is_constant():
-        return hop.inputconst(lltype.Bool, hop.s_result.const)
-
-    if hop.args_s[1].is_constant() and hop.args_s[1].const == list:
-        if hop.args_s[0].knowntype != list:
-            raise TyperError("isinstance(x, list) expects x to be known statically to be a list or None")
-        rlist = hop.args_r[0]
-        vlist = hop.inputarg(rlist, arg=0)
-        cnone = hop.inputconst(rlist, None)
-        return hop.genop('ptr_ne', [vlist, cnone], resulttype=lltype.Bool)
-
-    assert isinstance(hop.args_r[0], rclass.InstanceRepr)
-    return hop.args_r[0].rtype_isinstance(hop)
-
-def ll_instantiate(typeptr):   # NB. used by rpbc.ClassesPBCRepr as well
-    my_instantiate = typeptr.instantiate
-    return my_instantiate()
-
-def rtype_instantiate(hop):
-    hop.exception_cannot_occur()
-    s_class = hop.args_s[0]
-    assert isinstance(s_class, annmodel.SomePBC)
-    if len(s_class.descriptions) != 1:
-        # instantiate() on a variable class
-        vtypeptr, = hop.inputargs(rclass.get_type_repr(hop.rtyper))
-        v_inst = hop.gendirectcall(ll_instantiate, vtypeptr)
-        return hop.genop('cast_pointer', [v_inst],    # v_type implicit in r_result
-                         resulttype = hop.r_result.lowleveltype)
-
-    classdef = s_class.any_description().getuniqueclassdef()
-    return rclass.rtype_new_instance(hop.rtyper, classdef, hop.llops)
-
-def rtype_builtin_hasattr(hop):
-    hop.exception_cannot_occur()
-    if hop.s_result.is_constant():
-        return hop.inputconst(lltype.Bool, hop.s_result.const)
-
-    raise TyperError("hasattr is only suported on a constant")
-
-BUILTIN_TYPER = {}
-BUILTIN_TYPER[objectmodel.instantiate] = rtype_instantiate
-BUILTIN_TYPER[isinstance] = rtype_builtin_isinstance
-BUILTIN_TYPER[hasattr] = rtype_builtin_hasattr
-BUILTIN_TYPER[objectmodel.r_dict] = rtype_r_dict
-
-# _________________________________________________________________
-# weakrefs
-
-import weakref
-from rpython.rtyper.lltypesystem import llmemory
-
-def rtype_weakref_create(hop):
-    # Note: this code also works for the RPython-level calls 'weakref.ref(x)'.
-    vlist = hop.inputargs(hop.args_r[0])
-    hop.exception_cannot_occur()
-    return hop.genop('weakref_create', vlist, resulttype=llmemory.WeakRefPtr)
-
-def rtype_weakref_deref(hop):
-    c_ptrtype, v_wref = hop.inputargs(lltype.Void, hop.args_r[1])
-    assert v_wref.concretetype == llmemory.WeakRefPtr
-    hop.exception_cannot_occur()
-    return hop.genop('weakref_deref', [v_wref], resulttype=c_ptrtype.value)
-
-def rtype_cast_ptr_to_weakrefptr(hop):
-    vlist = hop.inputargs(hop.args_r[0])
-    hop.exception_cannot_occur()
-    return hop.genop('cast_ptr_to_weakrefptr', vlist,
-                     resulttype=llmemory.WeakRefPtr)
-
-def rtype_cast_weakrefptr_to_ptr(hop):
-    c_ptrtype, v_wref = hop.inputargs(lltype.Void, hop.args_r[1])
-    assert v_wref.concretetype == llmemory.WeakRefPtr
-    hop.exception_cannot_occur()
-    return hop.genop('cast_weakrefptr_to_ptr', [v_wref],
-                     resulttype=c_ptrtype.value)
-
-BUILTIN_TYPER[weakref.ref] = rtype_weakref_create
-BUILTIN_TYPER[llmemory.weakref_create] = rtype_weakref_create
-BUILTIN_TYPER[llmemory.weakref_deref] = rtype_weakref_deref
-BUILTIN_TYPER[llmemory.cast_ptr_to_weakrefptr] = rtype_cast_ptr_to_weakrefptr
-BUILTIN_TYPER[llmemory.cast_weakrefptr_to_ptr] = rtype_cast_weakrefptr_to_ptr

File rpython/rtyper/lltypesystem/rstr.py

View file
  • Ignore whitespace
 
     def ll_str2bytearray(str):
         from rpython.rtyper.lltypesystem.rbytearray import BYTEARRAY
-        
+
         lgt = len(str.chars)
         b = malloc(BYTEARRAY, lgt)
         for i in range(lgt):
 
         argsiter = iter(sourcevarsrepr)
 
-        InstanceRepr = hop.rtyper.type_system.rclass.InstanceRepr
+        from rpython.rtyper.lltypesystem.rclass import InstanceRepr
         for i, thing in enumerate(things):
             if isinstance(thing, tuple):
                 code = thing[0]
                 else:
                     raise TyperError("%%%s is not RPython" % (code,))
             else:
-                from rpython.rtyper.lltypesystem.rstr import string_repr, unicode_repr
                 if is_unicode:
                     vchunk = inputconst(unicode_repr, thing)
                 else:

File rpython/rtyper/lltypesystem/rtuple.py

  • Ignore whitespace
-from rpython.tool.pairtype import pairtype
-from rpython.rtyper.rmodel import inputconst
-from rpython.rtyper.rtuple import AbstractTupleRepr, AbstractTupleIteratorRepr
-from rpython.rtyper.lltypesystem.lltype import \
-     Ptr, GcStruct, Void, Signed, malloc, typeOf, nullptr
-from rpython.rtyper.lltypesystem.rtupletype import TUPLE_TYPE
-from rpython.rtyper.lltypesystem import rstr
-
-# ____________________________________________________________
-#
-#  Concrete implementation of RPython tuples:
-#
-#    struct tuple {
-#        type0 item0;
-#        type1 item1;
-#        type2 item2;
-#        ...
-#    }
-
-class TupleRepr(AbstractTupleRepr):
-    rstr_ll = rstr.LLHelpers
-
-    def __init__(self, rtyper, items_r):
-        AbstractTupleRepr.__init__(self, rtyper, items_r)
-        self.lowleveltype = TUPLE_TYPE(self.lltypes)
-
-    def newtuple(cls, llops, r_tuple, items_v):
-        # items_v should have the lowleveltype of the internal reprs
-        assert len(r_tuple.items_r) == len(items_v)
-        for r_item, v_item in zip(r_tuple.items_r, items_v):
-            assert r_item.lowleveltype == v_item.concretetype
-        #
-        if len(r_tuple.items_r) == 0:
-            return inputconst(Void, ())    # a Void empty tuple
-        c1 = inputconst(Void, r_tuple.lowleveltype.TO)
-        cflags = inputconst(Void, {'flavor': 'gc'})
-        v_result = llops.genop('malloc', [c1, cflags],
-                                         resulttype = r_tuple.lowleveltype)
-        for i in range(len(r_tuple.items_r)):
-            cname = inputconst(Void, r_tuple.fieldnames[i])
-            llops.genop('setfield', [v_result, cname, items_v[i]])
-        return v_result
-    newtuple = classmethod(newtuple)
-
-    def instantiate(self):
-        if len(self.items_r) == 0:
-            return dum_empty_tuple     # PBC placeholder for an empty tuple
-        else:
-            return malloc(self.lowleveltype.TO)
-
-    def rtype_bltn_list(self, hop):
-        from rpython.rtyper.lltypesystem import rlist
-        nitems = len(self.items_r)
-        vtup = hop.inputarg(self, 0)
-        LIST = hop.r_result.lowleveltype.TO
-        cno = inputconst(Signed, nitems)
-        hop.exception_is_here()
-        vlist = hop.gendirectcall(LIST.ll_newlist, cno)
-        v_func = hop.inputconst(Void, rlist.dum_nocheck)
-        for index in range(nitems):
-            name = self.fieldnames[index]
-            ritem = self.items_r[index]
-            cname = hop.inputconst(Void, name)
-            vitem = hop.genop('getfield', [vtup, cname], resulttype = ritem)
-            vitem = hop.llops.convertvar(vitem, ritem, hop.r_result.item_repr)
-            cindex = inputconst(Signed, index)
-            hop.gendirectcall(rlist.ll_setitem_nonneg, v_func, vlist, cindex, vitem)
-        return vlist
-
-    def getitem_internal(self, llops, v_tuple, index):
-        """Return the index'th item, in internal repr."""
-        name = self.fieldnames[index]
-        llresult = self.lltypes[index]
-        cname = inputconst(Void, name)
-        return  llops.genop('getfield', [v_tuple, cname], resulttype = llresult)
-
-
-def rtype_newtuple(hop):
-    return TupleRepr._rtype_newtuple(hop)
-
-newtuple = TupleRepr.newtuple
-
-def dum_empty_tuple(): pass
-
-
-# ____________________________________________________________
-#
-#  Iteration.
-
-class Length1TupleIteratorRepr(AbstractTupleIteratorRepr):
-
-    def __init__(self, r_tuple):
-        self.r_tuple = r_tuple
-        self.lowleveltype = Ptr(GcStruct('tuple1iter',
-                                         ('tuple', r_tuple.lowleveltype)))
-        self.ll_tupleiter = ll_tupleiter
-        self.ll_tuplenext = ll_tuplenext
-
-TupleRepr.IteratorRepr = Length1TupleIteratorRepr
-
-def ll_tupleiter(ITERPTR, tuple):
-    iter = malloc(ITERPTR.TO)
-    iter.tuple = tuple
-    return iter
-
-def ll_tuplenext(iter):
-    # for iterating over length 1 tuples only!
-    t = iter.tuple
-    if t:
-        iter.tuple = nullptr(typeOf(t).TO)
-        return t.item0
-    else:
-        raise StopIteration

File rpython/rtyper/lltypesystem/rtupletype.py

  • Ignore whitespace
-# Helper to build the lowleveltype corresponding to an RPython tuple.
-# This is not in rtuple.py so that it can be imported without bringing
-# the whole rtyper in.
-
-from rpython.rtyper.lltypesystem.lltype import Void, Ptr, GcStruct
-
-
-def TUPLE_TYPE(field_lltypes):
-    if len(field_lltypes) == 0:
-        return Void      # empty tuple
-    else:
-        fields = [('item%d' % i, TYPE) for i, TYPE in enumerate(field_lltypes)]
-        kwds = {'hints': {'immutable': True,
-                          'noidentity': True}}
-        return Ptr(GcStruct('tuple%d' % len(field_lltypes), *fields, **kwds))

File rpython/rtyper/module/ll_os_stat.py

View file
  • Ignore whitespace
 from rpython.rtyper.annlowlevel import hlstr
 from rpython.rtyper.extfunc import extdef
 from rpython.rtyper.lltypesystem import rffi, lltype
-from rpython.rtyper.lltypesystem.rtupletype import TUPLE_TYPE
+from rpython.rtyper.rtuple import TUPLE_TYPE
 from rpython.rtyper.tool import rffi_platform as platform
 from rpython.tool.pairtype import pairtype
 from rpython.tool.sourcetools import func_renamer

File rpython/rtyper/module/test/test_ll_os.py

View file
  • Ignore whitespace
     if not hasattr(os, 'statvfs'):
         py.test.skip('posix specific function')
     try:
-        expected = os.statvfs('.')
+        os.statvfs('.')
     except OSError, e:
         py.test.skip("the underlying os.statvfs() failed: %s" % e)
     getllimpl(os.statvfs)('.')
     if not hasattr(os, 'fstatvfs'):
         py.test.skip('posix specific function')
     try:
-        expected = os.fstatvfs(0)
+        os.fstatvfs(0)
     except OSError, e:
         py.test.skip("the underlying os.fstatvfs() failed: %s" % e)
     getllimpl(os.fstatvfs)(0)
     assert data == posix._getfullpathname(stuff)
     # the most intriguing failure of ntpath.py should not repeat, here:
     assert not data.endswith(stuff)
-    
+
 def test_getcwd():
     data = getllimpl(os.getcwd)()
     assert data == os.getcwd()
             # the ctypes call seems not to work in the Wing debugger
             return
         assert str(buf.value).lower() == pwd.lower()
-        # ctypes returns the drive letter in uppercase, 
-        # os.getcwd does not, 
+        # ctypes returns the drive letter in uppercase,
+        # os.getcwd does not,
         # but there may be uppercase in os.getcwd path
 
     pwd = os.getcwd()
     def setup_class(cls):
         if not hasattr(os, 'ttyname'):
             py.test.skip("no ttyname")
-    
+
     def test_ttyname(self):
         def f():
             import os
-            import py
             from rpython.rtyper.test.test_llinterp import interpret
 
             def ll_to_string(s):

File rpython/rtyper/module/test/test_ll_os_path.py

View file
  • Ignore whitespace
 import sys, os
 
 from rpython.rtyper.lltypesystem.module.ll_os_path import Implementation as impl
-from rpython.rtyper.module.support import ll_strcpy
 from rpython.rtyper.test.test_llinterp import interpret
 from rpython.tool.udir import udir
 
+
 def test_exists():
     filename = impl.to_rstr(str(py.path.local(__file__)))
     assert impl.ll_os_path_exists(filename) == True

File rpython/rtyper/rbuiltin.py

View file
  • Ignore whitespace
 from rpython.rlib import rarithmetic, objectmodel
 from rpython.rtyper import raddress, rptr, extregistry, rrange
 from rpython.rtyper.error import TyperError
-from rpython.rtyper.lltypesystem import lltype, llmemory
+from rpython.rtyper.lltypesystem import lltype, llmemory, rclass
+from rpython.rtyper.lltypesystem.rdict import rtype_r_dict
 from rpython.rtyper.rmodel import Repr
 from rpython.tool.pairtype import pairtype
 
         raise TyperError("**kwds call not implemented")
     if arguments.w_stararg is not None:
         # expand the *arg in-place -- it must be a tuple
-        from rpython.rtyper.rtuple import AbstractTupleRepr
+        from rpython.rtyper.rtuple import TupleRepr
         if arguments.w_stararg != hop.nb_args - 3:
             raise TyperError("call pattern too complex")
         hop.nb_args -= 1
         v_tuple = hop.args_v.pop()
         s_tuple = hop.args_s.pop()
         r_tuple = hop.args_r.pop()
-        if not isinstance(r_tuple, AbstractTupleRepr):
+        if not isinstance(r_tuple, TupleRepr):
             raise TyperError("*arg must be a tuple")
         for i in range(len(r_tuple.items_r)):
             v_item = r_tuple.getitem_internal(hop.llops, v_tuple, i)
             return BUILTIN_TYPER[self.builtinfunc]
         except (KeyError, TypeError):
             pass
-        try:
-            return rtyper.type_system.rbuiltin.BUILTIN_TYPER[self.builtinfunc]
-        except (KeyError, TypeError):
-            pass
         if extregistry.is_registered(self.builtinfunc):
             entry = extregistry.lookup(self.builtinfunc)
             return entry.specialize_call
 BUILTIN_TYPER[llmemory.cast_adr_to_ptr] = rtype_cast_adr_to_ptr
 BUILTIN_TYPER[llmemory.cast_adr_to_int] = rtype_cast_adr_to_int
 BUILTIN_TYPER[llmemory.cast_int_to_adr] = rtype_cast_int_to_adr
+
+def rtype_builtin_isinstance(hop):
+    hop.exception_cannot_occur()
+    if hop.s_result.is_constant():
+        return hop.inputconst(lltype.Bool, hop.s_result.const)
+
+    if hop.args_s[1].is_constant() and hop.args_s[1].const == list:
+        if hop.args_s[0].knowntype != list:
+            raise TyperError("isinstance(x, list) expects x to be known statically to be a list or None")
+        rlist = hop.args_r[0]
+        vlist = hop.inputarg(rlist, arg=0)
+        cnone = hop.inputconst(rlist, None)
+        return hop.genop('ptr_ne', [vlist, cnone], resulttype=lltype.Bool)
+
+    assert isinstance(hop.args_r[0], rclass.InstanceRepr)
+    return hop.args_r[0].rtype_isinstance(hop)
+
+def ll_instantiate(typeptr):   # NB. used by rpbc.ClassesPBCRepr as well
+    my_instantiate = typeptr.instantiate
+    return my_instantiate()
+
+def rtype_instantiate(hop):
+    hop.exception_cannot_occur()
+    s_class = hop.args_s[0]
+    assert isinstance(s_class, annmodel.SomePBC)
+    if len(s_class.descriptions) != 1:
+        # instantiate() on a variable class
+        vtypeptr, = hop.inputargs(rclass.get_type_repr(hop.rtyper))
+        v_inst = hop.gendirectcall(ll_instantiate, vtypeptr)
+        return hop.genop('cast_pointer', [v_inst],    # v_type implicit in r_result
+                         resulttype = hop.r_result.lowleveltype)
+
+    classdef = s_class.any_description().getuniqueclassdef()
+    return rclass.rtype_new_instance(hop.rtyper, classdef, hop.llops)
+
+def rtype_builtin_hasattr(hop):
+    hop.exception_cannot_occur()
+    if hop.s_result.is_constant():
+        return hop.inputconst(lltype.Bool, hop.s_result.const)
+
+    raise TyperError("hasattr is only suported on a constant")
+
+BUILTIN_TYPER[objectmodel.instantiate] = rtype_instantiate
+BUILTIN_TYPER[isinstance] = rtype_builtin_isinstance
+BUILTIN_TYPER[hasattr] = rtype_builtin_hasattr
+BUILTIN_TYPER[objectmodel.r_dict] = rtype_r_dict
+
+# _________________________________________________________________
+# weakrefs
+
+import weakref
+from rpython.rtyper.lltypesystem import llmemory
+
+def rtype_weakref_create(hop):
+    # Note: this code also works for the RPython-level calls 'weakref.ref(x)'.
+    vlist = hop.inputargs(hop.args_r[0])
+    hop.exception_cannot_occur()
+    return hop.genop('weakref_create', vlist, resulttype=llmemory.WeakRefPtr)
+
+def rtype_weakref_deref(hop):
+    c_ptrtype, v_wref = hop.inputargs(lltype.Void, hop.args_r[1])
+    assert v_wref.concretetype == llmemory.WeakRefPtr
+    hop.exception_cannot_occur()
+    return hop.genop('weakref_deref', [v_wref], resulttype=c_ptrtype.value)
+
+def rtype_cast_ptr_to_weakrefptr(hop):
+    vlist = hop.inputargs(hop.args_r[0])
+    hop.exception_cannot_occur()
+    return hop.genop('cast_ptr_to_weakrefptr', vlist,
+                     resulttype=llmemory.WeakRefPtr)
+
+def rtype_cast_weakrefptr_to_ptr(hop):
+    c_ptrtype, v_wref = hop.inputargs(lltype.Void, hop.args_r[1])
+    assert v_wref.concretetype == llmemory.WeakRefPtr
+    hop.exception_cannot_occur()
+    return hop.genop('cast_weakrefptr_to_ptr', [v_wref],
+                     resulttype=c_ptrtype.value)
+
+BUILTIN_TYPER[weakref.ref] = rtype_weakref_create
+BUILTIN_TYPER[llmemory.weakref_create] = rtype_weakref_create
+BUILTIN_TYPER[llmemory.weakref_deref] = rtype_weakref_deref
+BUILTIN_TYPER[llmemory.cast_ptr_to_weakrefptr] = rtype_cast_ptr_to_weakrefptr
+BUILTIN_TYPER[llmemory.cast_weakrefptr_to_ptr] = rtype_cast_weakrefptr_to_ptr

File rpython/rtyper/rbytearray.py

View file
  • Ignore whitespace
         return self.__class__,
 
     def rtyper_makerepr(self, rtyper):
-        return rtyper.type_system.rbytearray.bytearray_repr
+        from rpython.rtyper.lltypesystem.rbytearray import bytearray_repr
+        return bytearray_repr

File rpython/rtyper/rclass.py

View file
  • Ignore whitespace
 import types
 
+from rpython.flowspace.model import Constant
 from rpython.annotator import description, model as annmodel
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.lltypesystem.lltype import Void
 from rpython.rtyper.rmodel import Repr, getgcflavor, inputconst
+from rpython.rlib.objectmodel import UnboxedValue
 
 
 class FieldListAccessor(object):
     try:
         result = rtyper.class_reprs[classdef]
     except KeyError:
-        result = rtyper.type_system.rclass.ClassRepr(rtyper, classdef)
+        from rpython.rtyper.lltypesystem.rclass import ClassRepr
+        result = ClassRepr(rtyper, classdef)
         rtyper.class_reprs[classdef] = result
         rtyper.add_pendingsetup(result)
     return result
 
 
 def buildinstancerepr(rtyper, classdef, gcflavor='gc'):
-    from rpython.rlib.objectmodel import UnboxedValue
-    from rpython.flowspace.model import Constant
+    from rpython.rtyper.rvirtualizable2 import VirtualizableInstanceRepr
 
     if classdef is None:
         unboxed = []
     if virtualizable:
         assert len(unboxed) == 0
         assert gcflavor == 'gc'
-        return rtyper.type_system.rvirtualizable.VirtualizableInstanceRepr(rtyper, classdef)
-    elif usetagging and rtyper.type_system.name == 'lltypesystem':
+        return VirtualizableInstanceRepr(rtyper, classdef)
+    elif usetagging:
         # the UnboxedValue class and its parent classes need a
         # special repr for their instances
         if len(unboxed) != 1:
         from rpython.rtyper.lltypesystem import rtagged
         return rtagged.TaggedInstanceRepr(rtyper, classdef, unboxed[0])
     else:
-        return rtyper.type_system.rclass.InstanceRepr(rtyper, classdef, gcflavor)
+        from rpython.rtyper.lltypesystem.rclass import InstanceRepr
+        return InstanceRepr(rtyper, classdef, gcflavor)
 
 
 class MissingRTypeAttribute(TyperError):

File rpython/rtyper/rdict.py

View file
  • Ignore whitespace
 
 class __extend__(annmodel.SomeDict):
     def rtyper_makerepr(self, rtyper):
-        dictkey   = self.dictdef.dictkey
+        from rpython.rtyper.lltypesystem.rdict import DictRepr
+        dictkey = self.dictdef.dictkey
         dictvalue = self.dictdef.dictvalue
-        s_key     = dictkey  .s_value
-        s_value   = dictvalue.s_value
+        s_key = dictkey.s_value
+        s_value = dictvalue.s_value
         force_non_null = self.dictdef.force_non_null
         if dictkey.custom_eq_hash:
             custom_eq_hash = lambda: (rtyper.getrepr(dictkey.s_rdict_eqfn),
                                       rtyper.getrepr(dictkey.s_rdict_hashfn))
         else:
             custom_eq_hash = None
-        return rtyper.type_system.rdict.DictRepr(rtyper,
-                                                 lambda: rtyper.getrepr(s_key),
-                                                 lambda: rtyper.getrepr(s_value),
-                                                 dictkey,
-                                                 dictvalue,
-                                                 custom_eq_hash,
-                                                 force_non_null)
+        return DictRepr(rtyper, lambda: rtyper.getrepr(s_key),
+                        lambda: rtyper.getrepr(s_value), dictkey, dictvalue,
+                        custom_eq_hash, force_non_null)
 
     def rtyper_makekey(self):
         self.dictdef.dictkey  .dont_change_any_more = True
         return (self.__class__, self.dictdef.dictkey, self.dictdef.dictvalue)
 
 
-
 class AbstractDictRepr(rmodel.Repr):
 
     def pickrepr(self, item_repr):
     pickkeyrepr = pickrepr
 
     def compact_repr(self):
-        return 'DictR %s %s' % (self.key_repr.compact_repr(), self.value_repr.compact_repr())
+        return 'DictR %s %s' % (self.key_repr.compact_repr(),
+                                self.value_repr.compact_repr())
 
     def recast_value(self, llops, v):
         return llops.convertvar(v, self.value_repr, self.external_value_repr)
 
 
 def rtype_newdict(hop):
+    from rpython.rtyper.lltypesystem.rdict import ll_newdict
     hop.inputargs()    # no arguments expected
     r_dict = hop.r_result
     cDICT = hop.inputconst(lltype.Void, r_dict.DICT)
-    v_result = hop.gendirectcall(hop.rtyper.type_system.rdict.ll_newdict, cDICT)
+    v_result = hop.gendirectcall(ll_newdict, cDICT)
     return v_result
 
 

File rpython/rtyper/rfloat.py

View file
  • Ignore whitespace
 from rpython.annotator import model as annmodel
 from rpython.rlib.objectmodel import _hash_float
 from rpython.rlib.rarithmetic import base_int
+from rpython.rlib.rfloat import formatd
+from rpython.rlib import jit
+from rpython.rtyper.annlowlevel import llstr
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.lltypesystem.lltype import (Signed, Unsigned,
     SignedLongLong, UnsignedLongLong, Bool, Float)
 
 class __extend__(pairtype(AbstractStringRepr, FloatRepr)):
     def rtype_mod(_, hop):
-        rstr = hop.rtyper.type_system.rstr
-        return rstr.do_stringformat(hop, [(hop.args_v[1], hop.args_r[1])])
+        from rpython.rtyper.lltypesystem.rstr import do_stringformat
+        return do_stringformat(hop, [(hop.args_v[1], hop.args_r[1])])
 
 #Helpers FloatRepr,FloatRepr
 
     vlist = hop.inputargs(Float, Float)
     return hop.genop('float_'+func, vlist, resulttype=Bool)
 
-#
 
 class __extend__(FloatRepr):
 
         hop.exception_cannot_occur()
         return vlist[0]
 
-    # version picked by specialisation based on which
-    # type system rtyping is using, from <type_system>.ll_str module
+    @jit.elidable
     def ll_str(self, f):
-        pass
-    ll_str._annspecialcase_ = "specialize:ts('ll_str.ll_float_str')"
+        return llstr(formatd(f, 'f', 6))
 
 #
 # _________________________ Conversions _________________________

File rpython/rtyper/rint.py

View file
  • Ignore whitespace
 
 from rpython.annotator import model as annmodel
 from rpython.flowspace.operation import op_appendices
-from rpython.rlib import objectmodel
+from rpython.rlib import objectmodel, jit
 from rpython.rlib.rarithmetic import intmask, r_int, r_longlong
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.lltypesystem.lltype import (Signed, Unsigned, Bool, Float,
         hop.exception_cannot_occur()
         return vlist[0]
 
-    # version picked by specialisation based on which
-    # type system rtyping is using, from <type_system>.ll_str module
+    @jit.elidable
     def ll_str(self, i):
-        raise NotImplementedError
-    ll_str._annspecialcase_ = "specialize:ts('ll_str.ll_int_str')"
+        from rpython.rtyper.lltypesystem.ll_str import ll_int2dec
+        return ll_int2dec(i)
 
     def rtype_hex(self, hop):
+        from rpython.rtyper.lltypesystem.ll_str import ll_int2hex
         self = self.as_int
         varg = hop.inputarg(self, 0)
         true = inputconst(Bool, True)
-        fn = hop.rtyper.type_system.ll_str.ll_int2hex
-        return hop.gendirectcall(fn, varg, true)
+        return hop.gendirectcall(ll_int2hex, varg, true)
 
     def rtype_oct(self, hop):
+        from rpython.rtyper.lltypesystem.ll_str import ll_int2oct
         self = self.as_int
         varg = hop.inputarg(self, 0)
         true = inputconst(Bool, True)
-        fn = hop.rtyper.type_system.ll_str.ll_int2oct
-        return hop.gendirectcall(fn, varg, true)
+        return hop.gendirectcall(ll_int2oct, varg, true)
 
 def ll_hash_int(n):
     return intmask(n)

File rpython/rtyper/rlist.py

View file
  • Ignore whitespace
         listitem = self.listdef.listitem
         s_value = listitem.s_value
         if (listitem.range_step is not None and not listitem.mutated and
-            not isinstance(s_value, annmodel.SomeImpossibleValue)):
-            return rtyper.type_system.rrange.RangeRepr(listitem.range_step)
+                not isinstance(s_value, annmodel.SomeImpossibleValue)):
+            from rpython.rtyper.lltypesystem.rrange import RangeRepr
+            return RangeRepr(listitem.range_step)
         else:
             # cannot do the rtyper.getrepr() call immediately, for the case
             # of recursive structures -- i.e. if the listdef contains itself
-            rlist = rtyper.type_system.rlist
+            from rpython.rtyper.lltypesystem.rlist import ListRepr, FixedSizeListRepr
             item_repr = lambda: rtyper.getrepr(listitem.s_value)
             if self.listdef.listitem.resized:
-                return rlist.ListRepr(rtyper, item_repr, listitem)
+                return ListRepr(rtyper, item_repr, listitem)
             else:
-                return rlist.FixedSizeListRepr(rtyper, item_repr, listitem)
+                return FixedSizeListRepr(rtyper, item_repr, listitem)
 
     def rtyper_makekey(self):
         self.listdef.listitem.dont_change_any_more = True
 
 
 def rtype_newlist(hop, v_sizehint=None):
+    from rpython.rtyper.lltypesystem.rlist import newlist
     nb_args = hop.nb_args
     r_list = hop.r_result
     r_listitem = r_list.item_repr
     items_v = [hop.inputarg(r_listitem, arg=i) for i in range(nb_args)]
-    return hop.rtyper.type_system.rlist.newlist(hop.llops, r_list, items_v,