1. Pypy
  2. Untitled project
  3. pypy

Commits

nikomatsakis  committed d3c21ca

(niko, arigo and antocuni looking) merge fixed-list-ootype-2 branch to trunk,
introducing a different ootype type for lists that are not resized after
they are created.

  • Participants
  • Parent commits 1e8a3d0
  • Branches default

Comments (0)

Files changed (45)

File pypy/annotation/builtin.py

View file
     r = SomeOOInstance(ootype.typeOf(i))
     return r
 
+def oonewarray(s_type, length):
+    assert s_type.is_constant()
+    return SomeOOInstance(s_type.const)
+
 def null(I_OR_SM):
     assert I_OR_SM.is_constant()
     null = ootype.null(I_OR_SM.const)
 
 BUILTIN_ANALYZERS[ootype.instanceof] = instanceof
 BUILTIN_ANALYZERS[ootype.new] = new
+BUILTIN_ANALYZERS[ootype.oonewarray] = oonewarray
 BUILTIN_ANALYZERS[ootype.null] = null
 BUILTIN_ANALYZERS[ootype.runtimenew] = runtimenew
 BUILTIN_ANALYZERS[ootype.classof] = classof

File pypy/rpython/llinterp.py

View file
     def op_new(self, INST):
         assert isinstance(INST, (ootype.Instance, ootype.BuiltinType))
         return ootype.new(INST)
+        
+    def op_oonewarray(self, ARRAY, length):
+        assert isinstance(ARRAY, ootype.Array)
+        assert isinstance(length, int)
+        return ootype.oonewarray(ARRAY, length)
 
     def op_runtimenew(self, class_):
         return ootype.runtimenew(class_)

File pypy/rpython/lltypesystem/lloperation.py

View file
     'new':                  LLOp(oo=True, canraise=(Exception,)),
     'runtimenew':           LLOp(oo=True, canraise=(Exception,)),
     'oonewcustomdict':      LLOp(oo=True, canraise=(Exception,)),
+    'oonewarray':           LLOp(oo=True, canraise=(Exception,)),
     'oosetfield':           LLOp(oo=True),
     'oogetfield':           LLOp(oo=True, sideeffects=False),
     'oosend':               LLOp(oo=True, canraise=(Exception,)),

File pypy/rpython/ootypesystem/ootype.py

View file
             "ll_upper": Meth([], self.SELFTYPE_T),
             "ll_lower": Meth([], self.SELFTYPE_T),
             "ll_substring": Meth([Signed, Signed], self.SELFTYPE_T), # ll_substring(start, count)
-            "ll_split_chr": Meth([self.CHAR], List(self.SELFTYPE_T)),
+            "ll_split_chr": Meth([self.CHAR], Array(self.SELFTYPE_T)),
             "ll_contains": Meth([self.CHAR], Bool),
             "ll_replace_chr_chr": Meth([self.CHAR, self.CHAR], self.SELFTYPE_T),
             })
     ITEMTYPE_T = object()
 
     def __init__(self, ITEMTYPE=None):
-        self._ITEMTYPE = ITEMTYPE
+        self.ITEM = ITEMTYPE
         self._null = _null_list(self)
         if ITEMTYPE is not None:
             self._init_methods()
         # 'ITEMTYPE_T' is used as a placeholder for indicating
         # arguments that should have ITEMTYPE type. 'SELFTYPE_T' indicates 'self'
 
-        # XXX clean-up later! Rename _ITEMTYPE to ITEM.  For now they are
-        # just synonyms, please use ITEM in new code.
-        self.ITEM = self._ITEMTYPE
-
         generic_types = {
             self.SELFTYPE_T: self,
-            self.ITEMTYPE_T: self._ITEMTYPE,
+            self.ITEMTYPE_T: self.ITEM,
             }
 
         # the methods are named after the ADT methods of lltypesystem's lists
             return True
         if not isinstance(other, List):
             return False
-        if self._ITEMTYPE is None or other._ITEMTYPE is None:
+        if self.ITEM is None or other.ITEM is None:
             raise TypeError("Can't compare uninitialized List type.")
         return BuiltinADTType.__eq__(self, other)
 
         return not (self == other)
 
     def __hash__(self):
-        if self._ITEMTYPE is None:
+        if self.ITEM is None:
             raise TypeError("Can't hash uninitialized List type.")
         return BuiltinADTType.__hash__(self)    
 
     def __str__(self):
         return '%s(%s)' % (self.__class__.__name__,
-                saferecursive(str, "...")(self._ITEMTYPE))
+                saferecursive(str, "...")(self.ITEM))
 
     def _get_interp_class(self):
         return _list
 
     def _specialize(self, generic_types):
-        ITEMTYPE = self._specialize_type(self._ITEMTYPE, generic_types)
+        ITEMTYPE = self._specialize_type(self.ITEM, generic_types)
         return self.__class__(ITEMTYPE)
     
     def _defl(self):
         return self._null
 
     def _set_itemtype(self, ITEMTYPE):
-        self._ITEMTYPE = ITEMTYPE
+        self.ITEM = ITEMTYPE
         self._init_methods()
 
+    def ll_convert_from_array(self, array):
+        length = array.ll_length()
+        result = self.ll_newlist(length)
+        for n in range(length):
+            result.ll_setitem_fast(n, array.ll_getitem_fast(n))
+        return result
+
+class Array(BuiltinADTType):
+    # placeholders for types
+    # make sure that each derived class has his own SELFTYPE_T
+    # placeholder, because we want backends to distinguish that.
+    
+    SELFTYPE_T = object()
+    ITEMTYPE_T = object()
+
+    def __init__(self, ITEMTYPE=None):
+        self.ITEM = ITEMTYPE
+        self._null = _null_array(self)
+        if ITEMTYPE is not None:
+            self._init_methods()
+
+    def _init_methods(self):
+        # This defines the abstract list interface that backends will
+        # have to map to their native list implementations.
+        # 'ITEMTYPE_T' is used as a placeholder for indicating
+        # arguments that should have ITEMTYPE type. 'SELFTYPE_T' indicates 'self'
+
+        generic_types = {
+            self.SELFTYPE_T: self,
+            self.ITEMTYPE_T: self.ITEM,
+            }
+
+        # the methods are named after the ADT methods of lltypesystem's lists
+        self._GENERIC_METHODS = frozendict({
+            # "name": Meth([ARGUMENT1_TYPE, ARGUMENT2_TYPE, ...], RESULT_TYPE)
+            "ll_length": Meth([], Signed),
+            "ll_getitem_fast": Meth([Signed], self.ITEMTYPE_T),
+            "ll_setitem_fast": Meth([Signed, self.ITEMTYPE_T], Void),
+        })
+
+        self._setup_methods(generic_types)
+
+    def __eq__(self, other):
+        if self is other:
+            return True
+        if not isinstance(other, Array):
+            return False
+        if self.ITEM is None or other.ITEM is None:
+            raise TypeError("Can't compare uninitialized List type.")
+        return BuiltinADTType.__eq__(self, other)
+
+    def __ne__(self, other):
+        return not (self == other)
+
+    def __hash__(self):
+        if self.ITEM is None:
+            raise TypeError("Can't hash uninitialized List type.")
+        return BuiltinADTType.__hash__(self)    
+
+    def __str__(self):
+        return '%s(%s)' % (self.__class__.__name__,
+                saferecursive(str, "...")(self.ITEM))
+
+    def _get_interp_class(self):
+        return _array
+
+    def _specialize(self, generic_types):
+        ITEMTYPE = self._specialize_type(self.ITEM, generic_types)
+        return self.__class__(ITEMTYPE)
+
+    def _defl(self):
+        return self._null
+
+    def _example(self):
+        return oonewarray(self, 1)
+
+    def _set_itemtype(self, ITEMTYPE):
+        self.ITEM = ITEMTYPE
+        self._init_methods()
+
+    def ll_newlist(self, length):
+        from pypy.rpython.ootypesystem import rlist
+        return rlist.ll_newarray(self, length)
+
+    def ll_convert_from_array(self, array):
+        return array
 
 class Dict(BuiltinADTType):
     # placeholders for types
 
     def ll_split_chr(self, ch):
         # NOT_RPYTHON
-        res = _list(List(self._TYPE))
-        res._list = [self.make_string(s) for s in self._str.split(ch)]
+        l = [self.make_string(s) for s in self._str.split(ch)]
+        res = _array(Array(self._TYPE), len(l))
+        res._array[:] = l
         return res
 
     def ll_contains(self, ch):
     def __init__(self, WEAK_REFERENCE):
         self.__dict__["_TYPE"] = WEAK_REFERENCE
 
+
+
 class _list(_builtin_type):
     def __init__(self, LIST):
         self._TYPE = LIST
         # NOT_RPYTHON        
         if len(self._list) < length:
             diff = length - len(self._list)
-            self._list += [self._TYPE._ITEMTYPE._defl()] * diff
+            self._list += [self._TYPE.ITEM._defl()] * diff
         assert len(self._list) >= length
 
     def _ll_resize_le(self, length):
 
     def ll_setitem_fast(self, index, item):
         # NOT_RPYTHON
-        assert self._TYPE._ITEMTYPE is Void or typeOf(item) == self._TYPE._ITEMTYPE
+        assert self._TYPE.ITEM is Void or typeOf(item) == self._TYPE.ITEM
         assert typeOf(index) == Signed
         assert index >= 0
         self._list[index] = item
     def __init__(self, LIST):
         self.__dict__["_TYPE"] = LIST 
 
+class _array(_builtin_type):
+    def __init__(self, ARRAY, length):
+        self._TYPE = ARRAY
+        self._array = [ARRAY.ITEM._defl()] * length
+
+    def ll_length(self):
+        # NOT_RPYTHON
+        return len(self._array)
+
+    def ll_getitem_fast(self, index):
+        # NOT_RPYTHON
+        assert typeOf(index) == Signed
+        assert index >= 0
+        return self._array[index]
+
+    def ll_setitem_fast(self, index, item):
+        # NOT_RPYTHON
+        assert self._TYPE.ITEM is Void or typeOf(item) == self._TYPE.ITEM
+        assert typeOf(index) == Signed
+        assert index >= 0
+        self._array[index] = item
+
+class _null_array(_null_mixin(_array), _array):
+
+    def __init__(self, ARRAY):
+        self.__dict__["_TYPE"] = ARRAY 
+
 class _dict(_builtin_type):
     def __init__(self, DICT):
         self._TYPE = DICT
         return TYPE._get_interp_class()(TYPE)
 
 def oonewcustomdict(DICT, ll_eq, ll_hash):
+    """NOT_RPYTHON"""
     d = new(DICT)
     d.ll_set_functions(ll_eq, ll_hash)
     return d
 
+def oonewarray(ARRAY, length):
+    """NOT_RPYTHON"""
+    return _array(ARRAY, length)
+
 def runtimenew(class_):
     assert isinstance(class_, _class)
     assert class_ is not nullruntimeclass
     return LIST._set_itemtype(ITEMTYPE)
 
 def hasItemType(LIST):
-    return LIST._ITEMTYPE is not None
+    return LIST.ITEM is not None
 
 def setDictTypes(DICT, KEYTYPE, VALUETYPE):
     return DICT._set_types(KEYTYPE, VALUETYPE)

File pypy/rpython/ootypesystem/rbuiltin.py

View file
     return hop.genop('new', vlist,
                      resulttype = hop.r_result.lowleveltype)
 
+def rtype_oonewarray(hop):
+    assert hop.args_s[0].is_constant()
+    vlist = hop.inputarg(ootype.Void, arg=0)
+    vlength = hop.inputarg(ootype.Signed, arg=1)
+    return hop.genop('oonewarray', [vlist, vlength],
+                     resulttype = hop.r_result.lowleveltype)
+
 def rtype_null(hop):
     assert hop.args_s[0].is_constant()
     TYPE = hop.args_s[0].const
 
 BUILTIN_TYPER = {}
 BUILTIN_TYPER[ootype.new] = rtype_new
+BUILTIN_TYPER[ootype.oonewarray] = rtype_oonewarray
 BUILTIN_TYPER[ootype.null] = rtype_null
 BUILTIN_TYPER[ootype.classof] = rtype_classof
 BUILTIN_TYPER[ootype.subclassof] = rtype_subclassof

File pypy/rpython/ootypesystem/rdict.py

View file
 
 def ll_dict_kvi(d, LIST, func):
     length = d.ll_length()
-    result = ll_newlist(LIST, length)
+    result = LIST.ll_newlist(length)
     it = d.ll_get_items_iterator()
     i = 0
     while it.ll_go_next():
         elif func is dum_values:
             result.ll_setitem_fast(i, it.ll_current_value())
         if func is dum_items:
-            r = ootype.new(LIST._ITEMTYPE)
+            r = ootype.new(LIST.ITEM)
             r.item0 = it.ll_current_key()   # TODO: do we need casting?
             r.item1 = it.ll_current_value()
             result.ll_setitem_fast(i, r)

File pypy/rpython/ootypesystem/rlist.py

View file
 from pypy.tool.pairtype import pairtype
 from pypy.rpython.rlist import AbstractBaseListRepr, AbstractListRepr, \
-        AbstractListIteratorRepr, rtype_newlist, rtype_alloc_and_set
+        AbstractListIteratorRepr, AbstractFixedSizeListRepr, rtype_newlist, rtype_alloc_and_set
 from pypy.rpython.rmodel import Repr, IntegerRepr
 from pypy.rpython.rmodel import inputconst, externalvsinternal
 from pypy.rpython.lltypesystem.lltype import Signed, Void
         else:
             self.external_item_repr, self.item_repr = \
                     externalvsinternal(rtyper, item_repr)
-        self.LIST = ootype.List()
+        self.LIST = self._make_empty_type()
         self.lowleveltype = self.LIST
         self.listitem = listitem
         self.list_cache = {}
         # setup() needs to be called to finish this initialization
 
-    def _externalvsinternal(self, rtyper, item_repr):
-        return item_repr, item_repr
-    
     def _setup_repr(self):
         if 'item_repr' not in self.__dict__:
             self.external_item_repr, self.item_repr = \
         if not ootype.hasItemType(self.lowleveltype):
             ootype.setItemType(self.lowleveltype, self.item_repr.lowleveltype)
 
-    def null_const(self):
-        return self.LIST._null
-
-    def prepare_const(self, n):
-        result = self.LIST.ll_newlist(n)
-        return result
-
+    def _externalvsinternal(self, rtyper, item_repr):
+        return item_repr, item_repr
+    
     def send_message(self, hop, message, can_raise=False, v_args=None):
         if v_args is None:
             v_args = hop.inputargs(self, *hop.args_r[1:])
     def get_eqfunc(self):
         return inputconst(Void, self.item_repr.get_ll_eq_function())
 
-    def make_iterator_repr(self):
-        return ListIteratorRepr(self)
-
     def rtype_hint(self, hop):
         hints = hop.args_s[-1].const
         if 'maxlength' in hints:
 
 
 class ListRepr(AbstractListRepr, BaseListRepr):
+    def null_const(self):
+        return self.LIST._null
 
-    pass
+    def prepare_const(self, n):
+        result = self.LIST.ll_newlist(n)
+        return result
+        
+    def make_iterator_repr(self):
+        return ListIteratorRepr(self)
 
-FixedSizeListRepr = ListRepr
+    def _make_empty_type(self):
+        return ootype.List()
+
+    def _generate_newlist(self, llops, items_v, v_sizehint):
+        c_list = inputconst(ootype.Void, self.lowleveltype)
+        v_result = llops.genop("new", [c_list], resulttype=self.lowleveltype)
+        c_resize = inputconst(ootype.Void, "_ll_resize")
+        c_length = inputconst(ootype.Signed, len(items_v))
+        llops.genop("oosend", [c_resize, v_result, c_length], resulttype=ootype.Void)
+        return v_result
 
 class __extend__(pairtype(BaseListRepr, BaseListRepr)):
 
 
 def newlist(llops, r_list, items_v, v_sizehint=None):
     # XXX do something about v_sizehint
-    c_list = inputconst(ootype.Void, r_list.lowleveltype)
-    v_result = llops.genop("new", [c_list], resulttype=r_list.lowleveltype)
-    c_resize = inputconst(ootype.Void, "_ll_resize")
-    c_length = inputconst(ootype.Signed, len(items_v))
-    llops.genop("oosend", [c_resize, v_result, c_length], resulttype=ootype.Void)
+    v_result = r_list._generate_newlist(llops, items_v, v_sizehint)
 
     c_setitem = inputconst(ootype.Void, "ll_setitem_fast")
     for i, v_item in enumerate(items_v):
     lst._ll_resize(length)
     return lst
 
+# Fixed-size list 
+class FixedSizeListRepr(AbstractFixedSizeListRepr, BaseListRepr):
+    def compact_repr(self):
+        return 'FixedSizeListR %s' % (self.item_repr.compact_repr(),)
+
+    def _make_empty_type(self):
+        return ootype.Array()
+        
+    def null_const(self):
+        return self.LIST._null
+
+    def prepare_const(self, n):
+        return ll_newarray(self.LIST, n)
+
+    def make_iterator_repr(self):
+        return ListIteratorRepr(self)
+
+    def _generate_newlist(self, llops, items_v, v_sizehint):
+        c_array = inputconst(ootype.Void, self.lowleveltype)
+        c_length = inputconst(ootype.Signed, len(items_v))
+        v_result = llops.genop("oonewarray", [c_array, c_length], resulttype=self.lowleveltype)
+        return v_result
+
+def ll_newarray(ARRAY, length):
+    return ootype.oonewarray(ARRAY, length)
 
 # ____________________________________________________________
 #

File pypy/rpython/ootypesystem/rstr.py

View file
         return buf.ll_build()
 
     def ll_join_chars(length_dummy, lst):
-        if typeOf(lst)._ITEMTYPE == Char:
+        if typeOf(lst).ITEM == Char:
             buf = ootype.new(ootype.StringBuilder)
         else:
             buf = ootype.new(ootype.UnicodeBuilder)
         return buf.ll_build()
 
     def ll_join_strs(length_dummy, lst):
-        if typeOf(lst)._ITEMTYPE == ootype.String:
+        if typeOf(lst).ITEM == ootype.String:
             buf = ootype.new(ootype.StringBuilder)
         else:
             buf = ootype.new(ootype.UnicodeBuilder)
     def ll_stringslice_minusone(s):
         return s.ll_substring(0, s.ll_strlen()-1)
 
-    def ll_split_chr(LIST, s, c):
-        return s.ll_split_chr(c)
+    def ll_split_chr(RESULT, s, c):
+        return RESULT.ll_convert_from_array(s.ll_split_chr(c))
 
     def ll_int(s, base):
         if not 2 <= base <= 36:

File pypy/rpython/ootypesystem/rtuple.py

View file
     def rtype_bltn_list(self, hop):
         from pypy.rpython.ootypesystem import rlist
         v_tup = hop.inputarg(self, 0)
-        LIST = hop.r_result.lowleveltype
-        c_list = inputconst(ootype.Void, LIST)
-        v_list = hop.genop('new', [c_list], resulttype=LIST)
-        c_resize = inputconst(ootype.Void, '_ll_resize')
+        RESULT = hop.r_result.lowleveltype
+        c_resulttype = inputconst(ootype.Void, RESULT)
+        c_length = inputconst(ootype.Signed, len(self.items_r))
+        if isinstance(RESULT, ootype.Array):
+            v_list = hop.genop('oonewarray', [c_resulttype, c_length], resulttype=RESULT)
+        else:
+            assert isinstance(RESULT, ootype.List)
+            v_list = hop.genop('new', [c_resulttype], resulttype=RESULT)
+            c_resize = inputconst(ootype.Void, '_ll_resize')
+            hop.genop('oosend', [c_resize, v_list, c_length], resulttype=ootype.Void)
+
         c_setitem = inputconst(ootype.Void, 'll_setitem_fast')
-        c_length = inputconst(ootype.Signed, len(self.items_r))
-        hop.genop('oosend', [c_resize, v_list, c_length], resulttype=ootype.Void)
+        
         for index in range(len(self.items_r)):
             name = self.fieldnames[index]
             r_item = self.items_r[index]
             v_item = hop.llops.convertvar(v_item, r_item, hop.r_result.item_repr)
             c_index = inputconst(ootype.Signed, index)
             hop.genop('oosend', [c_setitem, v_list, c_index, v_item], resulttype=ootype.Void)
+            
         return v_list
 
 

File pypy/rpython/test/test_rlist.py

View file
         assert self.class_name(res) == 'A'
         #''.join(res.super.typeptr.name) == 'A\00'
         
-
     def test_reverse(self):
         def dummyfn():
             l = [5, 3, 2]
         assert res == 235
 
     def test_prebuilt_list(self):
-        klist = ['a', 'd', 'z', 'k']
+        klist = [6, 7, 8, 9]
         def dummyfn(n):
             return klist[n]
         res = self.interpret(dummyfn, [0])
-        assert res == 'a'
+        assert res == 6
         res = self.interpret(dummyfn, [3])
-        assert res == 'k'
+        assert res == 9
         res = self.interpret(dummyfn, [-2])
-        assert res == 'z'
+        assert res == 8
 
         klist = ['a', 'd', 'z']
         def mkdummyfn():

File pypy/rpython/test/tool.py

View file
         return OOSupport.to_runicode(u)
 
     def ll_to_list(self, l):
-        return l._list[:]
+        if hasattr(l, '_list'):
+            return l._list[:]
+        return l._array[:]
 
     def ll_unpack_tuple(self, t, length):
         return tuple([getattr(t, 'item%d' % i) for i in range(length)])

File pypy/translator/cli/constant.py

View file
 from pypy.translator.oosupport.constant import \
      push_constant, WeakRefConst, StaticMethodConst, CustomDictConst, \
      ListConst, ClassConst, InstanceConst, RecordConst, DictConst, \
-     BaseConstantGenerator, AbstractConst
+     BaseConstantGenerator, AbstractConst, ArrayConst
 from pypy.translator.cli.ilgenerator import CLIBaseGenerator
 from pypy.rpython.ootypesystem import ootype
 from pypy.translator.cli.comparer import EqualityComparer
     
     def create_pointer(self, gen):
         self.db.const_count.inc('List')
-        self.db.const_count.inc('List', self.value._TYPE._ITEMTYPE)
+        self.db.const_count.inc('List', self.value._TYPE.ITEM)
         self.db.const_count.inc('List', len(self.value._list))
-        super(CLIListConst, self).create_pointer(gen)        
+        super(CLIListConst, self).create_pointer(gen)
+
+
+class CLIArrayConst(CLIBaseConstMixin, ArrayConst):
+
+    def _do_not_initialize(self):
+        # Check if it is an array of all zeroes:
+        try:
+            if self.value._list == [0] * len(self.value._list):
+                return True
+        except:
+            pass
+        return super(CLIArrayConst, self)._do_not_initialize()
+
+    def _setitem(self, SELFTYPE, gen):
+        gen.array_setitem(SELFTYPE)
+
 
 class CLIDictConst(CLIDictMixin, DictConst):
     def create_pointer(self, gen):

File pypy/translator/cli/cts.py

View file
         arglist = ', '.join([arg.typename() for arg in self.arg_types])
         return '[%s]%s`%d<%s>' % (assembly, name, numparam, arglist)
 
+class CliArrayType(CliType):
+
+    def __init__(self, itemtype):
+        self.itemtype = itemtype
+
+    def typename(self):
+        return '%s[]' % self.itemtype.typename()
+
 
 T = CliPrimitiveType
 class types:
         elif isinstance(t, ootype.StaticMethod):
             delegate = self.db.record_delegate(t)
             return CliClassType(None, delegate)
+        elif isinstance(t, ootype.Array):
+            item_type = self.lltype_to_cts(t.ITEM)
+            if item_type == types.void: # special case: Array of Void
+                return types.list_of_void
+            return CliArrayType(item_type)
         elif isinstance(t, ootype.List):
-            item_type = self.lltype_to_cts(t._ITEMTYPE)
+            item_type = self.lltype_to_cts(t.ITEM)
             if item_type == types.void: # special case: List of Void
                 return types.list_of_void
             return types.list.specialize(item_type)

File pypy/translator/cli/entrypoint.py

View file
         ARG0 = graph.getargs()[0].concretetype
     except IndexError:
         ARG0 = None
-    if isinstance(ARG0, ootype.List) and ARG0._ITEMTYPE is ootype.String:
+    if isinstance(ARG0, ootype.List) and ARG0.ITEM is ootype.String:
         return StandaloneEntryPoint(graph)
     else:
         return TestEntryPoint(graph)
             ARG0 = self.graph.getargs()[0].concretetype
         except IndexError:
             ARG0 = None
-        assert isinstance(ARG0, ootype.List) and ARG0._ITEMTYPE is ootype.String,\
+        assert isinstance(ARG0, ootype.List) and ARG0.ITEM is ootype.String,\
                'Wrong entry point signature: List(String) expected'
 
         ilasm.begin_function('main', [('string[]', 'argv')], 'void', True, 'static')

File pypy/translator/cli/gencli.py

View file
     RecordConst = constant.CLIRecordConst
     ClassConst = constant.CLIClassConst
     ListConst = constant.CLIListConst
+    ArrayConst = constant.CLIArrayConst
     StaticMethodConst = constant.CLIStaticMethodConst
     CustomDictConst = constant.CLICustomDictConst
     DictConst = constant.CLIDictConst

File pypy/translator/cli/ilgenerator.py

View file
 
     def dup(self, TYPE):
         self.ilasm.opcode('dup')
+
+    def oonewarray(self, TYPE, length):
+        if TYPE.ITEM is ootype.Void:
+            self.new(TYPE)
+            self.ilasm.opcode('dup')
+            self.load(length)
+            self.ilasm.call_method('void [pypylib]pypy.runtime.ListOfVoid::_ll_resize(int32)', virtual=False)
+        else:
+            clitype = self.cts.lltype_to_cts(TYPE)
+            self.load(length)
+            self.ilasm.opcode('newarr', clitype.itemtype.typename())
+    
+    def _array_suffix(self, ARRAY, erase_unsigned=False):
+        from pypy.translator.cli.metavm import OOTYPE_TO_MNEMONIC
+        suffix = OOTYPE_TO_MNEMONIC.get(ARRAY.ITEM, 'ref')
+        if erase_unsigned:
+            suffix = suffix.replace('u', 'i')
+        return suffix
+
+    def array_setitem(self, ARRAY):
+        suffix = self._array_suffix(ARRAY, erase_unsigned=True)
+        self.ilasm.opcode('stelem.%s' % suffix)
+
+    def array_getitem(self, ARRAY):
+        self.ilasm.opcode('ldelem.%s' % self._array_suffix(ARRAY))
+
+    def array_length(self, ARRAY):
+        self.ilasm.opcode('ldlen')

File pypy/translator/cli/metavm.py

View file
             arg_list = ', '.join(arg_types)
             signature = '%s %s::%s(%s)' % (ret_type, STRING_HELPER_CLASS, method_name, arg_list)
             generator.call_signature(signature)
+        elif isinstance(this.concretetype, ootype.Array) and this.concretetype.ITEM is not ootype.Void:
+            v_array = args[0]
+            ARRAY = v_array.concretetype
+            if method_name == 'll_setitem_fast':
+                generator.array_setitem(ARRAY)
+            elif method_name == 'll_getitem_fast':
+                generator.array_getitem(ARRAY)
+            elif method_name == 'll_length':
+                generator.array_length(ARRAY)
+            else:
+                assert False
         else:
             generator.call_method(this.concretetype, method_name)
             
 
 
 OOTYPE_TO_MNEMONIC = {
+    ootype.Bool: 'i1', 
+    ootype.Char: 'i2',
+    ootype.UniChar: 'i2',
     ootype.Signed: 'i4',
     ootype.SignedLongLong: 'i8',
     ootype.Unsigned: 'u4',
     ootype.UnsignedLongLong: 'u8',
+    ootype.Float: 'r8',
     }
 
 class _CastPrimitive(MicroInstruction):

File pypy/translator/cli/oopspec.py

View file
 
 def get_method(TYPE, name):
     try:
-        # special case: when having List of Void, look at the concrete
-        # methods, not the generic ones
-        if isinstance(TYPE, ootype.List) and TYPE._ITEMTYPE is ootype.Void:
+        # special case: when having List of Void, or an Array, look at
+        # the concrete methods, not the generic ones
+        if isinstance(TYPE, ootype.Array) or (isinstance(TYPE, ootype.List) and TYPE.ITEM is ootype.Void):
             return TYPE._METHODS[name]
         else:
             return TYPE._GENERIC_METHODS[name]

File pypy/translator/cli/opcodes.py

View file
      TypeOf, CastPrimitive, EventHandler, GetStaticField, SetStaticField,\
      FieldInfoForConst
 from pypy.translator.oosupport.metavm import PushArg, PushAllArgs, StoreResult, InstructionList,\
-    New, RuntimeNew, CastTo, PushPrimitive, OOString, OOUnicode
+    New, RuntimeNew, CastTo, PushPrimitive, OOString, OOUnicode, OONewArray
 from pypy.translator.cli.cts import WEAKREF
 from pypy.rpython.ootypesystem import ootype
 
     'ooparse_int':              [PushAllArgs, 'call int32 [pypylib]pypy.runtime.Utils::OOParseInt(string, int32)'],
     'ooparse_float':            [PushAllArgs, 'call float64 [pypylib]pypy.runtime.Utils::OOParseFloat(string)'],
     'oonewcustomdict':          [NewCustomDict],
+    'oonewarray':               [OONewArray, StoreResult],
     
     'hint':                     [PushArg(0), StoreResult],
     'direct_call':              [Call],

File pypy/translator/cli/src/pypylib.cs

View file
         public static string ToPython(object x) {
             if (x == null)
                 return "None";
+            else if (x is Array)
+                return ArrayToPython((Array)x);
             else
                 return x.ToString();
         }
 
+        private static string ArrayToPython(Array array)
+        {
+            string res = "[";
+            foreach(object item in array) {
+                if (item != null && item.GetType() == typeof(string)) {
+                    object tmp = (object)item;
+                    res += ToPython((string)tmp) + ",";
+                }
+                else
+                    res += ToPython(item) + ",";
+                
+            }
+            res += "]";
+            return res;
+        }
+
         public static string InstanceToPython(object obj) 
         { 
             return string.Format("InstanceWrapper('{0}')", obj.GetType().FullName);
             return s.Substring(start, count);
         }
 
-        public static List<string> ll_split_chr(string s, char ch)
+        public static string[] ll_split_chr(string s, char ch)
         {
-            List<string> res = new List<string>();
-            res.AddRange(s.Split(ch));
-            return res;
+            return s.Split(ch);
         }
 
         public static bool ll_contains(string s, char ch)
                     res += pypy.test.Result.ToPython((string)tmp) + ",";
                 }
                 else
-                    res += item.ToString() + ","; // XXX: doesn't work for chars
+                    res += pypy.test.Result.ToPython(item) + ",";
             }
             res += "]";
             return res;

File pypy/translator/cli/test/test_list.py

View file
 import py
 from pypy.translator.cli.test.runtest import CliTest
 from pypy.rpython.test.test_rlist import BaseTestRlist
+from pypy.rlib.rarithmetic import r_uint
 
 class TestCliList(CliTest, BaseTestRlist):
     def test_recursive(self):
 
     def test_getitem_exc(self):
         py.test.skip('fixme!')
+
+    def test_list_unsigned(self):
+        def fn(x):
+            lst = [r_uint(0), r_uint(1)]
+            lst[0] = r_uint(x)
+            return lst[0]
+        res = self.interpret(fn, [42])
+        assert res == 42
+
+    def test_list_bool(self):
+        def fn(x):
+            lst = [True, False]
+            lst[0] = x
+            return lst[0]
+        res = self.interpret(fn, [False])
+        assert res == False

File pypy/translator/js/asmgen.py

View file
     def runtimenew(self):
         self.right_hand.append("new %s()" % self.right_hand.pop())
     
+    def oonewarray(self, obj, length):
+        self.right_hand.append("new %s(%s)" % (obj, length))
+
     def load_self(self):
         self.right_hand.append("this")
     

File pypy/translator/js/database.py

View file
             return InstanceConst(db, const, static_type)
         elif isinstance(const, ootype._list):
             return ListConst(db, const)
+        elif isinstance(const, ootype._array):
+            return ListConst(db, const)
         elif isinstance(const, ootype._record):
             return RecordConst(db, const)
         elif isinstance(const, ootype._string):
 
 class ListConst(AbstractConst):
     
+    def _get_list(self):
+        if isinstance(self.const, ootype._list):
+            return self.const._list
+        else:
+            return self.const._array
+
+
     def get_name(self):
         return "const_list"
     
         if not self.const:
             return
         
-        for i in self.const._list:
+        for i in self._get_list():
             name = self.db.record_const(i, None, 'const')
             if name is not None:
                 self.depends.add(name)
         if not self.const:
             return
         
-        for i in xrange(len(self.const._list)):
+        l = self._get_list()
+        for i in xrange(len(l)):
             ilasm.load_str("%s.%s"%(const_var.name, name))
-            el = self.const._list[i]
+            el = l[i]
             self.db.load_const(typeOf(el), el, ilasm)
             self.db.load_const(typeOf(i), i, ilasm)
             ilasm.list_setitem()

File pypy/translator/js/function.py

View file
     def new(self, obj):
         self.ilasm.new(self.cts.obj_name(obj))
 
+    def oonewarray(self, obj, length):
+        self.ilasm.oonewarray(self.cts.obj_name(obj), length)
+
     def set_field(self, obj, name):
         self.ilasm.set_field(obj, name)
         #self.ilasm.set_field(self.field_name(obj,name))

File pypy/translator/js/jsbuiltin.py

View file
                 '_ll_resize_le' : list_resize,
                 'll_length' : _GetPredefinedField('length'),
             },
+            ootype.Array: {
+                'll_setitem_fast' : ListSetitem,
+                'll_getitem_fast' : ListGetitem,
+                'll_length' : _GetPredefinedField('length'),
+            },
             ootype.Dict: {
                 'll_get' : ListGetitem,
                 'll_set' : ListSetitem,

File pypy/translator/js/jts.py

View file
             return self.escape_name(t._name)
         elif isinstance(t, ootype.List):
             return "Array"
+        elif isinstance(t, ootype.Array):
+            return "Array"
         elif isinstance(t, lltype.Primitive):
             return "var"
         elif isinstance(t, ootype.Record):
 ##        elif isinstance(t, ootype.StaticMethod):
 ##            return 'void' # TODO: is it correct to ignore StaticMethod?
 ##        elif isinstance(t, ootype.List):
-##            item_type = self.lltype_to_cts(t._ITEMTYPE)
+##            item_type = self.lltype_to_cts(t.ITEM)
 ##            return self.__class(PYPY_LIST % item_type, include_class)
 ##        elif isinstance(t, ootype.Dict):
 ##            key_type = self.lltype_to_cts(t._KEYTYPE)

File pypy/translator/js/opcodes.py

View file
 """
 
 from pypy.translator.oosupport.metavm import PushArg, PushAllArgs, StoreResult,\
-    InstructionList, New, GetField, MicroInstruction, RuntimeNew, PushPrimitive
+    InstructionList, New, GetField, MicroInstruction, RuntimeNew, PushPrimitive,\
+    OONewArray
      
 from pypy.translator.oosupport.metavm import _GetFieldDispatcher, _SetFieldDispatcher, \
     _CallDispatcher, _MethodDispatcher, SetField
     'indirect_call' : [IndirectCall],
     'same_as' : CopyName,
     'new' : [New],
+    'oonewarray' : [OONewArray],
     'runtimenew' : [RuntimeNew],
     'instanceof' : [IsInstance],
     #'subclassof' : [IsSubclassOf],

File pypy/translator/jvm/builtin.py

View file
-from pypy.translator.jvm import typesystem as jvmtype
-from pypy.translator.jvm import generator as jvmgen
+import pypy.translator.jvm.typesystem as jvm
 from pypy.rpython.ootypesystem import ootype
 from pypy.translator.jvm.typesystem import \
      jInt, jVoid, jStringBuilder, jString, jPyPy, jChar, jArrayList, jObject, \
 # ______________________________________________________________________
 # Mapping of built-in OOTypes to JVM types
 
-class JvmBuiltInType(jvmtype.JvmClassType):
+class JvmBuiltInType(jvm.JvmClassType):
     
     """
     Represents built-in types to JVM.  May optionally be associated
     """
     
     def __init__(self, db, classty, OOTYPE):
-        jvmtype.JvmClassType.__init__(self, classty.name)
+        jvm.JvmClassType.__init__(self, classty.name)
         self.db = db
         self.OOTYPE = OOTYPE
         self.gen = Generifier(OOTYPE)
         return hash(self.name)
 
     def lookup_field(self, fieldnm):
-        """ Given a field name, returns a jvmgen.Field object """
+        """ Given a field name, returns a jvm.Field object """
         _, FIELDTY = self.OOTYPE._lookup_field(fieldnm)
         jfieldty = self.db.lltype_to_cts(FIELDTY)
-        return jvmgen.Field(
+        return jvm.Field(
             self.descriptor.class_name(), fieldnm, jfieldty, False)
 
     def lookup_method(self, methodnm):
-        """ Given the method name, returns a jvmgen.Method object """
+        """ Given the method name, returns a jvm.Method object """
 
         # Look for a shortcut method in our table of remappings:
         try:
         if self.OOTYPE.__class__ in bridged_objects:
             # Bridged objects are ones where we have written a java class
             # that has methods with the correct names and types already
-            return jvmgen.Method.v(self, methodnm, jargtypes, jrettype)
+            return jvm.Method.v(self, methodnm, jargtypes, jrettype)
         else:
             # By default, we assume it is a static method on the PyPy
             # object, that takes an instance of this object as the first
             # argument.  The other arguments we just convert to java versions,
             # except for generics.
             jargtypes = [self] + jargtypes
-            return jvmgen.Method.s(jPyPy, methodnm, jargtypes, jrettype)
+            return jvm.Method.s(jPyPy, methodnm, jargtypes, jrettype)
 
 # When we lookup a method on a BuiltInClassNode, we first check the
 # 'built_in_methods' and 'bridged_objects' tables.  This allows us to
     # .__class__ is required
     
     (ootype.StringBuilder.__class__, "ll_allocate"):
-    jvmgen.Method.v(jStringBuilder, "ensureCapacity", (jInt,), jVoid),
+    jvm.Method.v(jStringBuilder, "ensureCapacity", (jInt,), jVoid),
     
     (ootype.StringBuilder.__class__, "ll_build"):
-    jvmgen.Method.v(jStringBuilder, "toString", (), jString),
+    jvm.Method.v(jStringBuilder, "toString", (), jString),
 
     (ootype.String.__class__, "ll_streq"):
-    jvmgen.Method.v(jString, "equals", (jObject,), jBool),
+    jvm.Method.v(jString, "equals", (jObject,), jBool),
 
     (ootype.String.__class__, "ll_strlen"):
-    jvmgen.Method.v(jString, "length", (), jInt),
+    jvm.Method.v(jString, "length", (), jInt),
     
     (ootype.String.__class__, "ll_stritem_nonneg"):
-    jvmgen.Method.v(jString, "charAt", (jInt,), jChar),
+    jvm.Method.v(jString, "charAt", (jInt,), jChar),
 
     (ootype.String.__class__, "ll_startswith"):
-    jvmgen.Method.v(jString, "startsWith", (jString,), jBool),
+    jvm.Method.v(jString, "startsWith", (jString,), jBool),
 
     (ootype.String.__class__, "ll_endswith"):
-    jvmgen.Method.v(jString, "endsWith", (jString,), jBool),
+    jvm.Method.v(jString, "endsWith", (jString,), jBool),
 
     (ootype.String.__class__, "ll_strcmp"):
-    jvmgen.Method.v(jString, "compareTo", (jString,), jInt),
+    jvm.Method.v(jString, "compareTo", (jString,), jInt),
 
     (ootype.String.__class__, "ll_upper"):
-    jvmgen.Method.v(jString, "toUpperCase", (), jString),
+    jvm.Method.v(jString, "toUpperCase", (), jString),
 
     (ootype.String.__class__, "ll_lower"):
-    jvmgen.Method.v(jString, "toLowerCase", (), jString),
+    jvm.Method.v(jString, "toLowerCase", (), jString),
 
     (ootype.String.__class__, "ll_replace_chr_chr"):
-    jvmgen.Method.v(jString, "replace", (jChar, jChar), jString),
+    jvm.Method.v(jString, "replace", (jChar, jChar), jString),
 
     (ootype.Dict, "ll_set"):
-    jvmgen.Method.v(jHashMap, "put", (jObject, jObject), jObject),
+    jvm.Method.v(jHashMap, "put", (jObject, jObject), jObject),
     
     (ootype.Dict, "ll_get"):
-    jvmgen.Method.v(jHashMap, "get", (jObject,), jObject),
+    jvm.Method.v(jHashMap, "get", (jObject,), jObject),
 
     (ootype.Dict, "ll_contains"):
-    jvmgen.Method.v(jHashMap, "containsKey", (jObject,), jBool),
+    jvm.Method.v(jHashMap, "containsKey", (jObject,), jBool),
 
     (ootype.Dict, "ll_length"):
-    jvmgen.Method.v(jHashMap, "size", (), jInt),
+    jvm.Method.v(jHashMap, "size", (), jInt),
     
     (ootype.Dict, "ll_clear"):
-    jvmgen.Method.v(jHashMap, "clear", (), jVoid),
+    jvm.Method.v(jHashMap, "clear", (), jVoid),
 
     (ootype.CustomDict, "ll_set"):
-    jvmgen.Method.v(jPyPyCustomDict, "put", (jObject, jObject), jObject),
+    jvm.Method.v(jPyPyCustomDict, "put", (jObject, jObject), jObject),
     
     (ootype.CustomDict, "ll_get"):
-    jvmgen.Method.v(jPyPyCustomDict, "get", (jObject,), jObject),
+    jvm.Method.v(jPyPyCustomDict, "get", (jObject,), jObject),
 
     (ootype.CustomDict, "ll_contains"):
-    jvmgen.Method.v(jPyPyCustomDict, "containsKey", (jObject,), jBool),
+    jvm.Method.v(jPyPyCustomDict, "containsKey", (jObject,), jBool),
 
     (ootype.CustomDict, "ll_length"):
-    jvmgen.Method.v(jPyPyCustomDict, "size", (), jInt),
+    jvm.Method.v(jPyPyCustomDict, "size", (), jInt),
     
     (ootype.CustomDict, "ll_clear"):
-    jvmgen.Method.v(jPyPyCustomDict, "clear", (), jVoid),
+    jvm.Method.v(jPyPyCustomDict, "clear", (), jVoid),
 
     (ootype.List, "ll_length"):
-    jvmgen.Method.v(jArrayList, "size", (), jInt),
+    jvm.Method.v(jArrayList, "size", (), jInt),
 
     (ootype.List, "ll_getitem_fast"):
-    jvmgen.Method.v(jArrayList, "get", (jInt,), jObject),
+    jvm.Method.v(jArrayList, "get", (jInt,), jObject),
 
     }
 

File pypy/translator/jvm/cmpopcodes.py

View file
-from pypy.translator.jvm.generator import \
+from pypy.translator.jvm.typesystem import \
      IFLT, IFLE, IFEQ, IFNE, IFGT, IFGE, \
      IFNONNULL, IF_ACMPEQ, GOTO, ICONST, \
      DCONST_0, DCMPG, LCONST_0, LCMP, \
      IF_ICMPLT, IF_ICMPLE, IF_ICMPEQ, IF_ICMPNE, IF_ICMPGT, IF_ICMPGE, \
-     PYPYUINTCMP, PYPYULONGCMP, \
+     PYPYUINTCMP, PYPYULONGCMP
+
+from pypy.translator.jvm.generator import \
      Label
 
 ##### Branch directly as the result of a comparison

File pypy/translator/jvm/constant.py

View file
 from pypy.rpython.ootypesystem import ootype
 from pypy.objspace.flow import model as flowmodel
-from pypy.translator.jvm.generator import \
-     Field, Method, CUSTOMDICTMAKE
+import pypy.translator.jvm.typesystem as jvm
+from pypy.translator.jvm.typesystem import \
+     jVoid, Method, Field
 from pypy.translator.oosupport.constant import \
      BaseConstantGenerator, RecordConst, InstanceConst, ClassConst, \
      StaticMethodConst, CustomDictConst, WeakRefConst, push_constant, \
      MAX_CONST_PER_STEP
-from pypy.translator.jvm.typesystem import \
-     jObject, jVoid, jPyPyWeakRef, JvmClassType
 
-jPyPyConstantInit = JvmClassType('pypy.ConstantInit')
+jPyPyConstantInit = jvm.JvmClassType('pypy.ConstantInit')
 jPyPyConstantInitMethod = Method.s(jPyPyConstantInit, 'init', [], jVoid)
 
 # ___________________________________________________________________________
         # This prevents any one class from getting too big.
         if (self.num_constants % MAX_CONST_PER_STEP) == 0:
             cc_num = len(self.ccs)
-            self.ccs.append(JvmClassType('pypy.Constant_%d' % cc_num))
+            self.ccs.append(jvm.JvmClassType('pypy.Constant_%d' % cc_num))
         self.num_constants += 1
 
         const.fieldobj = Field(self.ccs[-1].name, const.name, jfieldty, True)
             except KeyError:
                 constants_by_cls[const.fieldobj.class_name] = [const]
         for cc in self.ccs:
-            ilasm.begin_class(cc, jObject)
+            ilasm.begin_class(cc, jvm.jObject)
             for const in constants_by_cls[cc.name]:
                 ilasm.add_field(const.fieldobj)
             ilasm.end_class()
             self._push_constant_during_init(gen, const)
 
     def _declare_step(self, gen, stepnum):
-        self.step_classes.append(JvmClassType('pypy.ConstantInit_%d' % stepnum))
-        gen.begin_class(self.step_classes[-1], jObject)
+        self.step_classes.append(jvm.JvmClassType(
+            'pypy.ConstantInit_%d' % stepnum))
+        gen.begin_class(self.step_classes[-1], jvm.jObject)
         gen.begin_function('constant_init', [], [], jVoid, True)
 
     def _close_step(self, gen, stepnum):
         gen.end_class()       # end pypy.ConstantInit_NNN
     
     def _end_gen_constants(self, gen, numsteps):
-        gen.begin_class(jPyPyConstantInit, jObject)
+        gen.begin_class(jPyPyConstantInit, jvm.jObject)
         gen.begin_j_function(jPyPyConstantInit, jPyPyConstantInitMethod)
         for cls in self.step_classes:
             m = Method.s(cls, "constant_init", [], jVoid)
         if self.delegate_impl:
             gen.new_with_jtype(self.delegate_impl)
         else:
-            gen.push_null(jObject)
+            gen.push_null(jvm.jObject)
 
     def initialize_data(self, constgen, gen):
         return
     def create_pointer(self, gen):
         gen.new_with_jtype(self.eq_jcls)
         gen.new_with_jtype(self.hash_jcls)
-        gen.emit(CUSTOMDICTMAKE)
+        gen.emit(jvm.CUSTOMDICTMAKE)
         
 class JVMWeakRefConst(WeakRefConst):
 
     PRIORITY = 200
 
     def jtype(self):
-        return jPyPyWeakRef
+        return jvm.jPyPyWeakRef
 
     def create_pointer(self, gen):        
         if not self.value:

File pypy/translator/jvm/database.py

View file
 from pypy.rpython.lltypesystem import lltype
 from pypy.rpython.ootypesystem import ootype, rclass
 from pypy.rpython.ootypesystem.module import ll_os
-from pypy.translator.jvm import typesystem as jvmtype
 from pypy.translator.jvm import node, methods
 from pypy.translator.jvm.option import getoption
-import pypy.translator.jvm.generator as jvmgen
-from pypy.translator.jvm.generator import Method, Property, Field
-import pypy.translator.jvm.constant as jvmconst
-from pypy.translator.jvm.typesystem import \
-     jStringBuilder, jInt, jVoid, jString, jChar, jObject, \
-     jThrowable, JvmNativeClass, jPyPy, JvmClassType
 from pypy.translator.jvm.builtin import JvmBuiltInType
-
 from pypy.translator.oosupport.database import Database as OODatabase
 from pypy.rpython.ootypesystem.bltregistry import ExternalType
 from pypy.annotation.signature import annotation
 from pypy.annotation.model import annotation_to_lltype
+import pypy.translator.jvm.constant as jvmconst
+import pypy.translator.jvm.typesystem as jvm
 
 # ______________________________________________________________________
 # Database object
         self._jasmin_files = [] # list of strings --- .j files we made
         self._classes = {} # Maps ootype class objects to node.Class objects,
                            # and JvmType objects as well
-        self._functions = {}      # graph -> jvmgen.Method
+        self._functions = {}      # graph -> jvm.Method
 
         # (jargtypes, jrettype) -> node.StaticMethodInterface
         self._delegates = {}
 
         self._function_names = {} # graph --> function_name
 
-        self._constants = {}      # flowmodel.Variable --> jvmgen.Const
+        self._constants = {}      # flowmodel.Variable --> jvm.Const
 
         # Special fields for the Object class, see _translate_Object
         self._object_interf = None
         #
         #    These are public attributes that are referenced from
         #    elsewhere in the code using
-        #    jvmgen.Generator.push_interlink() and .push_pypy().
-        self.jPyPyMain = JvmClassType(self._pkg('Main'))
-        self.pypy_field = jvmgen.Field.s(self.jPyPyMain, 'pypy', jPyPy)
-        self.interlink_field = jvmgen.Field.s(self.jPyPyMain, 'ilink',
-                                              jvmtype.jPyPyInterlink)
+        #    jvm.Generator.push_interlink() and .push_pypy().
+        self.jPyPyMain = jvm.JvmClassType(self._pkg('Main'))
+        self.pypy_field = jvm.Field.s(self.jPyPyMain, 'pypy', jvm.jPyPy)
+        self.interlink_field = jvm.Field.s(self.jPyPyMain, 'ilink',
+                                           jvm.jPyPyInterlink)
 
     # _________________________________________________________________
     # Java String vs Byte Array
 
     def class_name(self, TYPE):
         jtype = self.lltype_to_cts(TYPE)
-        assert isinstance(jtype, jvmtype.JvmClassType)
+        assert isinstance(jtype, jvm.JvmClassType)
         return jtype.name
 
     def add_jasmin_file(self, jfile):
         like.
 
         The 'methods' argument should be a dictionary whose keys are
-        method names and whose entries are jvmgen.Method objects which
+        method names and whose entries are jvm.Method objects which
         the corresponding method should invoke. """
 
         nm = self._pkg(self._uniq('InterlinkImplementation'))
-        cls = node.Class(nm, supercls=jObject)
+        cls = node.Class(nm, supercls=jvm.jObject)
         for method_name, helper in methods.items():
             cls.add_method(node.InterlinkFunction(cls, method_name, helper))
-        cls.add_interface(jvmtype.jPyPyInterlink)
+        cls.add_interface(jvm.jPyPyInterlink)
         self.jInterlinkImplementation = cls
         self.pending_node(cls)
 
 
         # Create the class object first
         clsnm = self._pkg(self._uniq('Record'))
-        clsobj = node.Class(clsnm, jObject)
+        clsobj = node.Class(clsnm, jvm.jObject)
         self._classes[OOTYPE] = clsobj
 
         # Add fields:
         def gen_name(): return self._pkg(self._uniq(OBJ._name))
         internm, implnm, exc_implnm = gen_name(), gen_name(), gen_name()
         self._object_interf = node.Interface(internm)
-        self._object_impl = node.Class(implnm, supercls=jObject)
-        self._object_exc_impl = node.Class(exc_implnm, supercls=jThrowable)
+        self._object_impl = node.Class(implnm, supercls=jvm.jObject)
+        self._object_exc_impl = node.Class(exc_implnm, supercls=jvm.jThrowable)
         self._object_impl.add_interface(self._object_interf)
         self._object_exc_impl.add_interface(self._object_interf)
 
             methodnm = "_jvm_"+fieldnm
 
             def getter_method_obj(node):
-                return Method.v(node, methodnm+"_g", [], fieldty)
+                return jvm.Method.v(node, methodnm+"_g", [], fieldty)
             def putter_method_obj(node):
-                return Method.v(node, methodnm+"_p", [fieldty], jVoid)
+                return jvm.Method.v(node, methodnm+"_p", [fieldty], jvm.jVoid)
             
             # Add get/put methods to the interface:
-            prop = Property(
+            prop = jvm.Property(
                 fieldnm, 
                 getter_method_obj(self._object_interf),
                 putter_method_obj(self._object_interf),
             # Generate implementations:
             def generate_impl(clsobj):
                 clsnm = clsobj.name
-                fieldobj = Field(clsnm, fieldnm, fieldty, False, FIELDOOTY)
+                fieldobj = jvm.Field(clsnm, fieldnm, fieldty, False, FIELDOOTY)
                 clsobj.add_field(fieldobj, fielddef)
                 clsobj.add_method(node.GetterFunction(
                     self, clsobj, getter_method_obj(clsobj), fieldobj))
                 arglist = [self.lltype_to_cts(ARG) for ARG in METH.ARGS
                            if ARG is not ootype.Void]
                 returntype = self.lltype_to_cts(METH.RESULT)
-                clsobj.add_abstract_method(jvmgen.Method.v(
+                clsobj.add_abstract_method(jvm.Method.v(
                     clsobj, mname, arglist, returntype))
             else:
                 # if the first argument's type is not a supertype of
             if FIELDOOTY is ootype.Void: continue
             fieldty = self.lltype_to_cts(FIELDOOTY)
             clsobj.add_field(
-                jvmgen.Field(clsobj.name, fieldnm, fieldty, False, FIELDOOTY),
+                jvm.Field(clsobj.name, fieldnm, fieldty, False, FIELDOOTY),
                 fielddef)
 
     def pending_class(self, OOTYPE):
         This is invoked when a standalone function is to be compiled.
         It creates a class named after the function with a single
         method, invoke().  This class is added to the worklist.
-        Returns a jvmgen.Method object that allows this function to be
+        Returns a jvm.Method object that allows this function to be
         invoked.
         """
         if graph in self._functions:
         """
         Like record_delegate, but the signature is in terms of java
         types.  jargs is a list of JvmTypes, one for each argument,
-        and jret is a JvmType.  Note that jargs does NOT include an
+        and jret is a Jvm.  Note that jargs does NOT include an
         entry for the this pointer of the resulting object.  
         """
         key = (jargs, jret)
     # any type.
     
     _toString_methods = {
-        ootype.Signed:jvmgen.INTTOSTRINGI,
-        ootype.Unsigned:jvmgen.PYPYSERIALIZEUINT,
-        ootype.SignedLongLong:jvmgen.LONGTOSTRINGL,
-        ootype.UnsignedLongLong: jvmgen.PYPYSERIALIZEULONG,
-        ootype.Float:jvmgen.DOUBLETOSTRINGD,
-        ootype.Bool:jvmgen.PYPYSERIALIZEBOOLEAN,
-        ootype.Void:jvmgen.PYPYSERIALIZEVOID,
-        ootype.Char:jvmgen.PYPYESCAPEDCHAR,
-        ootype.UniChar:jvmgen.PYPYESCAPEDUNICHAR,
-        ootype.String:jvmgen.PYPYESCAPEDSTRING,
-        ootype.Unicode:jvmgen.PYPYESCAPEDUNICODE,
+        ootype.Signed:jvm.INTTOSTRINGI,
+        ootype.Unsigned:jvm.PYPYSERIALIZEUINT,
+        ootype.SignedLongLong:jvm.LONGTOSTRINGL,
+        ootype.UnsignedLongLong: jvm.PYPYSERIALIZEULONG,
+        ootype.Float:jvm.DOUBLETOSTRINGD,
+        ootype.Bool:jvm.PYPYSERIALIZEBOOLEAN,
+        ootype.Void:jvm.PYPYSERIALIZEVOID,
+        ootype.Char:jvm.PYPYESCAPEDCHAR,
+        ootype.UniChar:jvm.PYPYESCAPEDUNICHAR,
+        ootype.String:jvm.PYPYESCAPEDSTRING,
+        ootype.Unicode:jvm.PYPYESCAPEDUNICODE,
         }
 
     def toString_method_for_ootype(self, OOTYPE):
 
         to print the value of 'var'.
         """
-        return self._toString_methods.get(OOTYPE, jvmgen.PYPYSERIALIZEOBJECT)
+        return self._toString_methods.get(OOTYPE, jvm.PYPYSERIALIZEOBJECT)
 
     # _________________________________________________________________
     # Type translation functions
     # Dictionary for scalar types; in this case, if we see the key, we
     # will return the value
     ootype_to_scalar = {
-        ootype.Void:             jvmtype.jVoid,
-        ootype.Signed:           jvmtype.jInt,
-        ootype.Unsigned:         jvmtype.jInt,
-        ootype.SignedLongLong:   jvmtype.jLong,
-        ootype.UnsignedLongLong: jvmtype.jLong,
-        ootype.Bool:             jvmtype.jBool,
-        ootype.Float:            jvmtype.jDouble,
-        ootype.Char:             jvmtype.jChar,    # byte would be sufficient, but harder
-        ootype.UniChar:          jvmtype.jChar,
-        ootype.Class:            jvmtype.jClass,
-        ootype.ROOT:             jvmtype.jObject,  # treat like a scalar
+        ootype.Void:             jvm.jVoid,
+        ootype.Signed:           jvm.jInt,
+        ootype.Unsigned:         jvm.jInt,
+        ootype.SignedLongLong:   jvm.jLong,
+        ootype.UnsignedLongLong: jvm.jLong,
+        ootype.Bool:             jvm.jBool,
+        ootype.Float:            jvm.jDouble,
+        ootype.Char:             jvm.jChar,    # byte would be sufficient, but harder
+        ootype.UniChar:          jvm.jChar,
+        ootype.Class:            jvm.jClass,
+        ootype.ROOT:             jvm.jObject,  # treat like a scalar
     }
 
     # Dictionary for non-scalar types; in this case, if we see the key, we
     # will return a JvmBuiltInType based on the value
     ootype_to_builtin = {
-        ootype.String:           jvmtype.jString,
-        ootype.Unicode:          jvmtype.jString,
-        ootype.StringBuilder:    jvmtype.jStringBuilder,
-        ootype.UnicodeBuilder:   jvmtype.jStringBuilder,
-        ootype.List:             jvmtype.jArrayList,
-        ootype.Dict:             jvmtype.jHashMap,
-        ootype.DictItemsIterator:jvmtype.jPyPyDictItemsIterator,
-        ootype.CustomDict:       jvmtype.jPyPyCustomDict,
-        ootype.WeakReference:    jvmtype.jPyPyWeakRef,
-        ll_os.STAT_RESULT:       jvmtype.jPyPyStatResult,
+        ootype.String:           jvm.jString,
+        ootype.Unicode:          jvm.jString,
+        ootype.StringBuilder:    jvm.jStringBuilder,
+        ootype.UnicodeBuilder:   jvm.jStringBuilder,
+        ootype.List:             jvm.jArrayList,
+        ootype.Dict:             jvm.jHashMap,
+        ootype.DictItemsIterator:jvm.jPyPyDictItemsIterator,
+        ootype.CustomDict:       jvm.jPyPyCustomDict,
+        ootype.WeakReference:    jvm.jPyPyWeakRef,
+        ll_os.STAT_RESULT:       jvm.jPyPyStatResult,
 
         # These are some configured records that are generated by Java
         # code.  
         #ootype.Record({"item0": ootype.Signed, "item1": ootype.Signed}):
-        #jvmtype.jPyPyRecordSignedSigned,
+        #jvm.jPyPyRecordSignedSigned,
         #ootype.Record({"item0": ootype.Float, "item1": ootype.Signed}):
-        #jvmtype.jPyPyRecordFloatSigned,
+        #jvm.jPyPyRecordFloatSigned,
         #ootype.Record({"item0": ootype.Float, "item1": ootype.Float}):
-        #jvmtype.jPyPyRecordFloatFloat,
+        #jvm.jPyPyRecordFloatFloat,
         #ootype.Record({"item0": ootype.String, "item1": ootype.String}):
-        #jvmtype.jPyPyRecordStringString,        
+        #jvm.jPyPyRecordStringString,        
         }
 
     def lltype_to_cts(self, OOT):
+        import sys
+        res = self._lltype_to_cts(OOT)
+        return res
+
+    def _lltype_to_cts(self, OOT):
         """ Returns an instance of JvmType corresponding to
         the given OOType """
 
             return self.ootype_to_scalar[OOT]
         if (isinstance(OOT, lltype.Ptr) and
             isinstance(OOT.TO, lltype.OpaqueType)):
-            return jObject
+            return jvm.jObject
         if OOT in self.ootype_to_builtin:
             return JvmBuiltInType(self, self.ootype_to_builtin[OOT], OOT)
+        if isinstance(OOT, ootype.Array):
+            return self._array_type(OOT.ITEM)
         if OOT.__class__ in self.ootype_to_builtin:
             return JvmBuiltInType(
                 self, self.ootype_to_builtin[OOT.__class__], OOT)
 
         # handle externals
         if isinstance(OOT, ExternalType):
-            return JvmNativeClass(self, OOT)
+            return jvm.JvmNativeClass(self, OOT)
         
         assert False, "Untranslatable type %s!" % OOT
 
+    ooitemtype_to_array = {
+        ootype.Signed   : jvm.jIntArray,
+        ootype.Unsigned : jvm.jIntArray,
+        ootype.Char     : jvm.jCharArray,
+        ootype.Bool     : jvm.jBoolArray,
+        ootype.UniChar  : jvm.jCharArray,
+        ootype.String   : jvm.jStringArray,
+        ootype.Float    : jvm.jDoubleArray,
+        ootype.Void     : jvm.jVoidArray,
+    }
+
+    def _array_type(self, ITEM):
+        if ITEM in self.ooitemtype_to_array:
+            return self.ooitemtype_to_array[ITEM]
+        return jvm.jObjectArray
+
     def annotation_to_cts(self, _tp):
         s_tp = annotation(_tp)
         TP = annotation_to_lltype(s_tp)

File pypy/translator/jvm/generator.py

View file
 from pypy.rlib.objectmodel import CDefinedIntSymbolic
 from pypy.rlib.rarithmetic import isnan, isinf
 from pypy.translator.oosupport.constant import push_constant
-import pypy.translator.jvm.typesystem as jvmtype
+import pypy.translator.jvm.typesystem as jvm
+
+# Load a few commonly used names, but prefer to use 'jvm.Name'
 from pypy.translator.jvm.typesystem import \
-     JvmType, jString, jInt, jLong, jDouble, jBool, jString, \
-     jPyPy, jVoid, jMath, desc_for_method, jPrintStream, jClass, jChar, \
-     jObject, jByteArray, jPyPyExcWrap, jIntegerClass, jLongClass, \
-     jDoubleClass, jCharClass, jStringBuilder, JvmScalarType, jArrayList, \
-     jObjectArray, jPyPyInterlink, jPyPyCustomDict, jPyPyEquals, \
-     jPyPyHashCode, jMap, jPyPyWeakRef, jSystem, jll_os, jPyPyInterlink
-
-
-# ___________________________________________________________________________
-# JVM Opcodes:
-#
-#   Map from symbolic name to an instance of the Opcode class
-
-class Opcode(object):
-    def __init__(self, jvmstr):
-        """
-        flags is a set of flags (see above) that describe opcode #UPDATE
-        jvmstr is the name for jasmin printouts
-        """
-        self.jvmstr = jvmstr
-        self.flags = None #Should flags be added to args?
-
-    def __repr__(self):
-        return "<Opcode %s:%x>" % (self.jvmstr, self.flags)
-
-    def specialize(self, args):
-        """ Process the argument list according to the various flags.
-        Returns a tuple (OPCODE, ARGS) where OPCODE is a string representing
-        the new opcode, and ARGS is a list of arguments or empty tuple.
-        Most of these do not do anything. """
-        return (self.jvmstr, args)
-
-class IntConstOpcode(Opcode):
-    """ The ICONST opcode specializes itself for small integer opcodes. """
-    def specialize(self, args):
-        assert len(args) == 1
-        if args[0] == -1:
-            return self.jvmstr + "_m1", ()
-        elif args[0] >= 0 and args[0] <= 5:
-            return self.jvmstr + "_" + str(args[0]), ()
-        # Non obvious: convert ICONST to LDC if the constant is out of
-        # range
-        return "ldc", args
-
-class VarOpcode(Opcode):
-    """ An Opcode which takes a variable index as an argument; specialized
-    to small integer indices. """
-    def specialize(self, args):
-        assert len(args) == 1
-        if args[0] >= 0 and args[0] <= 3:
-            return self.jvmstr + "_" + str(args[0]), ()
-        return Opcode.specialize(self, args)
-
-class IntClassNameOpcode(Opcode):
-    """ An opcode which takes an internal class name as its argument;
-    the actual argument will be a JvmType instance. """
-    def specialize(self, args):
-        args = [args[0].descriptor.int_class_name()]
-        return self.jvmstr, args
-        
-class OpcodeFamily(object):
-    """
-    Many opcodes in JVM have variants that depend on the type of the
-    operands; for example, one must choose the correct ALOAD, ILOAD,
-    or DLOAD depending on whether one is loading a reference, integer,
-    or double variable respectively.  Each instance of this class
-    defines one 'family' of opcodes, such as the LOAD family shown
-    above, and produces Opcode objects specific to a particular type.
-    """
-    def __init__(self, opcclass, suffix):
-        """
-        opcclass is the opcode subclass to use (see above) when
-        instantiating a particular opcode
-        
-        jvmstr is the name for jasmin printouts
-        """
-        self.opcode_class = opcclass
-        self.suffix = suffix
-        self.cache = {}
-
-    def _o(self, prefix):
-        try:
-            return self.cache[prefix]
-        except KeyError:
-            self.cache[prefix] = obj = self.opcode_class(
-                prefix+self.suffix)
-            return obj
-        
-    def for_type(self, argtype):
-        """ Returns a customized opcode of this family appropriate to
-        'argtype', a JvmType object. """
-
-        desc = argtype.descriptor
-
-        # These are always true:
-        if desc[0] == 'L': return self._o("a")   # Objects
-        if desc[0] == '[': return self._o("a")   # Arrays
-        if desc == 'I':    return self._o("i")   # Integers
-        if desc == 'J':    return self._o("l")   # Integers
-        if desc == 'D':    return self._o("d")   # Doubles
-        if desc == 'V':    return self._o("")    # Void [used by RETURN]
-
-        # Chars/Bytes/Booleans are normally represented as ints
-        # in the JVM, but some opcodes are different.  They use a
-        # different OpcodeFamily (see ArrayOpcodeFamily for ex)
-        if desc == 'C':    return self._o("i")   # Characters
-        if desc == 'B':    return self._o("i")   # Bytes
-        if desc == 'Z':    return self._o("i")   # Boolean
-
-        assert False, "Unknown argtype=%s" % repr(argtype)
-        raise NotImplementedError
-
-class ArrayOpcodeFamily(OpcodeFamily):
-    """ Opcode family specialized for array access instr """
-    def for_type(self, argtype):
-        desc = argtype.descriptor
-        if desc == 'J':    return self._o("l")   # Integers
-        if desc == 'D':    return self._o("d")   # Doubles
-        if desc == 'C':    return self._o("c")   # Characters
-        if desc == 'B':    return self._o("b")   # Bytes
-        if desc == 'Z':    return self._o("b")   # Boolean (access as bytes)
-        return OpcodeFamily.for_type(self, argtype)
-
-# Define the opcodes for IFNE, IFEQ, IFLT, IF_ICMPLT, etc.  The IFxx
-# variants compare a single integer arg against 0, and the IF_ICMPxx
-# variants compare 2 integer arguments against each other.
-for cmpop in ('ne', 'eq', 'lt', 'gt', 'le', 'ge'):
-    ifop = "if%s" % cmpop
-    if_icmpop = "if_icmp%s" % cmpop
-    globals()[ifop.upper()] = Opcode(ifop)
-    globals()[if_icmpop.upper()] = Opcode(if_icmpop)
-
-# Compare references, either against NULL or against each other
-IFNULL =    Opcode('ifnull')
-IFNONNULL = Opcode('ifnonnull')
-IF_ACMPEQ = Opcode('if_acmpeq')
-IF_ACMPNE = Opcode('if_acmpne')
-
-# Method invocation
-INVOKESTATIC = Opcode('invokestatic')
-INVOKEVIRTUAL = Opcode('invokevirtual')
-INVOKESPECIAL = Opcode('invokespecial')
-INVOKEINTERFACE = Opcode('invokeinterface')
-
-# Other opcodes
-LDC =       Opcode('ldc')       # single-word types
-LDC2 =      Opcode('ldc2_w')    # double-word types: doubles and longs
-GOTO =      Opcode('goto')
-ICONST =    IntConstOpcode('iconst')
-ICONST_0 =  Opcode('iconst_0')  # sometimes convenient to refer to this directly
-ACONST_NULL=Opcode('aconst_null')
-DCONST_0 =  Opcode('dconst_0')
-DCONST_1 =  Opcode('dconst_1')
-LCONST_0 =  Opcode('lconst_0')
-LCONST_1 =  Opcode('lconst_1')
-GETFIELD =  Opcode('getfield')
-PUTFIELD =  Opcode('putfield')
-GETSTATIC = Opcode('getstatic')
-PUTSTATIC = Opcode('putstatic')
-CHECKCAST = IntClassNameOpcode('checkcast')
-INEG =      Opcode('ineg')
-IXOR =      Opcode('ixor')
-IADD =      Opcode('iadd')
-ISUB =      Opcode('isub')
-IMUL =      Opcode('imul')
-IDIV =      Opcode('idiv')
-IREM =      Opcode('irem')
-IAND =      Opcode('iand')
-IOR =       Opcode('ior')
-ISHL =      Opcode('ishl')
-ISHR =      Opcode('ishr')
-IUSHR =     Opcode('iushr')
-LCMP =      Opcode('lcmp')
-DCMPG =     Opcode('dcmpg')
-DCMPL =     Opcode('dcmpl')
-NOP =       Opcode('nop')
-I2D =       Opcode('i2d')
-I2L =       Opcode('i2l')
-D2I=        Opcode('d2i')
-#D2L=        Opcode('d2l') #PAUL
-L2I =       Opcode('l2i')
-L2D =       Opcode('l2d')
-ATHROW =    Opcode('athrow')
-DNEG =      Opcode('dneg')
-DADD =      Opcode('dadd')
-DSUB =      Opcode('dsub')
-DMUL =      Opcode('dmul')
-DDIV =      Opcode('ddiv')
-DREM =      Opcode('drem')
-LNEG =      Opcode('lneg')
-LADD =      Opcode('ladd')
-LSUB =      Opcode('lsub')
-LMUL =      Opcode('lmul')
-LDIV =      Opcode('ldiv')
-LREM =      Opcode('lrem')
-LAND =      Opcode('land')
-LOR =       Opcode('lor')
-LXOR =      Opcode('lxor')
-LSHL =      Opcode('lshl')
-LSHR =      Opcode('lshr')
-LUSHR =     Opcode('lushr')
-NEW =       IntClassNameOpcode('new')
-DUP =       Opcode('dup')
-DUP2 =      Opcode('dup2')
-DUP_X1 =    Opcode('dup_x1')
-POP =       Opcode('pop')
-POP2 =      Opcode('pop2')
-SWAP =      Opcode('swap')
-INSTANCEOF= IntClassNameOpcode('instanceof')
-# Loading/storing local variables
-LOAD =      OpcodeFamily(VarOpcode, "load")
-STORE =     OpcodeFamily(VarOpcode, "store")
-RETURN =    OpcodeFamily(Opcode, "return")
-
-# Loading/storing from arrays
-#   *NOTE*: This family is characterized by the type of the ELEMENT,
-#   not the type of the ARRAY.  
-#   
-#   Also: here I break from convention by naming the objects ARRLOAD
-#   rather than ALOAD, even though the suffix is 'aload'.  This is to
-#   avoid confusion with the ALOAD opcode.
-ARRLOAD =      ArrayOpcodeFamily(Opcode, "aload")
-ARRSTORE =     ArrayOpcodeFamily(Opcode, "astore")
+     jPyPy, jString, jInt, jVoid
 
 # ___________________________________________________________________________
 # Labels
         return self.label
     
 # ___________________________________________________________________________
-# Methods
-#
-# "Method" objects describe all the information needed to invoke a
-# method.  We create one for each node.Function object, as well as for
-# various helper methods (defined below).  To invoke a method, you
-# push its arguments and then use generator.emit(methobj) where
-# methobj is its Method instance.
-
-class Method(object):
-
-    # Create a constructor:
-    def c(classty, argtypes):
-        return Method(classty.name, "<init>", argtypes, jVoid,
-                      opcode=INVOKESPECIAL)
-    c = staticmethod(c)
-
-    # Create a virtual or interface method:
-    def v(classty, methnm, argtypes, rettype):
-        """
-        Shorthand to create a virtual method.
-        'class' - JvmType object for the class
-        'methnm' - name of the method (Python string)
-        'argtypes' - list of JvmType objects, one for each argument but
-        not the this ptr
-        'rettype' - JvmType for return type
-        """
-        assert argtypes is not None
-        assert rettype is not None
-        classnm = classty.name
-        if isinstance(classty, jvmtype.JvmInterfaceType):
-            opc = INVOKEINTERFACE
-        else:
-            assert isinstance(classty, jvmtype.JvmClassType)
-            opc = INVOKEVIRTUAL
-        return Method(classnm, methnm, argtypes, rettype, opcode=opc)
-    v = staticmethod(v)
-
-    # Create a static method:
-    def s(classty, methnm, argtypes, rettype):
-        """
-        Shorthand to create a static method.
-        'class' - JvmType object for the class
-        'methnm' - name of the method (Python string)
-        'argtypes' - list of JvmType objects, one for each argument but
-        not the this ptr
-        'rettype' - JvmType for return type
-        """
-        assert isinstance(classty, JvmType)
-        classnm = classty.name
-        return Method(classnm, methnm, argtypes, rettype)
-    s = staticmethod(s)
-    
-    def __init__(self, classnm, methnm, argtypes, rettype, opcode=INVOKESTATIC):
-        self.opcode = opcode
-        self.class_name = classnm  # String, ie. "java.lang.Math"
-        self.method_name = methnm  # String "abs"
-        self.argument_types = argtypes # List of jvmtypes
-        self.return_type = rettype     # jvmtype
-
-        # Compute the method descriptior, which is a string like "()I":
-        argtypesdesc = [a.descriptor for a in argtypes]
-        rettypedesc = rettype.descriptor
-        self.descriptor = desc_for_method(argtypesdesc, rettypedesc)  
-    def invoke(self, gen):
-        gen._instr(self.opcode, self)        
-    def is_static(self):
-        return self.opcode == INVOKESTATIC
-    def jasmin_syntax(self):
-        res = "%s/%s%s" % (self.class_name.replace('.','/'),
-                           self.method_name,
-                           self.descriptor)
-        # A weird, inexplicable quirk of Jasmin syntax is that it requires
-        # the number of arguments after an invokeinterface call:
-        if self.opcode == INVOKEINTERFACE:
-            res += " %d" % (len(self.argument_types)+1,)
-        return res
-
-OBJHASHCODE =           Method.v(jObject, 'hashCode', (), jInt)
-OBJTOSTRING =           Method.v(jObject, 'toString', (), jString)
-OBJEQUALS =             Method.v(jObject, 'equals', (jObject,), jBool)
-SYSTEMGC =              Method.s(jSystem, 'gc', (), jVoid)
-INTTOSTRINGI =          Method.s(jIntegerClass, 'toString', (jInt,), jString)
-LONGTOSTRINGL =         Method.s(jLongClass, 'toString', (jLong,), jString)
-DOUBLETOSTRINGD =       Method.s(jDoubleClass, 'toString', (jDouble,), jString)
-CHARTOSTRINGC =         Method.s(jCharClass, 'toString', (jChar,), jString)
-MATHIABS =              Method.s(jMath, 'abs', (jInt,), jInt)
-IABSOVF =               Method.v(jPyPy, 'abs_ovf', (jInt,), jInt)
-MATHLABS =              Method.s(jMath, 'abs', (jLong,), jLong)
-LABSOVF =               Method.v(jPyPy, 'abs_ovf', (jLong,), jLong)
-MATHDABS =              Method.s(jMath, 'abs', (jDouble,), jDouble)
-INEGOVF =               Method.v(jPyPy, 'negate_ovf', (jInt,), jInt)
-LNEGOVF =               Method.v(jPyPy, 'negate_ovf', (jLong,), jLong)
-IADDOVF =               Method.v(jPyPy, 'add_ovf', (jInt, jInt), jInt)
-LADDOVF =               Method.v(jPyPy, 'add_ovf', (jLong, jLong), jLong)
-ISUBOVF =               Method.v(jPyPy, 'subtract_ovf', (jInt, jInt), jInt)
-LSUBOVF =               Method.v(jPyPy, 'subtract_ovf', (jLong, jLong), jLong)
-IMULOVF =               Method.v(jPyPy, 'multiply_ovf', (jInt, jInt), jInt)
-LMULOVF =               Method.v(jPyPy, 'multiply_ovf', (jLong, jLong), jLong)
-MATHFLOOR =             Method.s(jMath, 'floor', (jDouble,), jDouble)
-IFLOORDIVOVF =          Method.v(jPyPy, 'floordiv_ovf', (jInt, jInt), jInt)
-LFLOORDIVOVF =          Method.v(jPyPy, 'floordiv_ovf', (jLong, jLong), jLong)
-IFLOORDIVZEROVF =       Method.v(jPyPy, 'floordiv_zer_ovf', (jInt, jInt), jInt)