[pypy-svn] r73315 - in pypy/branch/avm/pypy/translator: . avm1 avm1/.ropeproject avm1/test avm2 avm2/test tool

magcius at codespeak.net magcius at codespeak.net
Sat Apr 3 01:46:33 CEST 2010


Author: magcius
Date: Sat Apr  3 01:46:31 2010
New Revision: 73315

Added:
   pypy/branch/avm/pypy/translator/avm2/library.py
Removed:
   pypy/branch/avm/pypy/translator/avm1/.ropeproject/
   pypy/branch/avm/pypy/translator/avm1/records_flymake.py
   pypy/branch/avm/pypy/translator/avm1/test/harness_flymake.py
Modified:
   pypy/branch/avm/pypy/translator/avm1/avm1.py
   pypy/branch/avm/pypy/translator/avm1/avm1gen.py
   pypy/branch/avm/pypy/translator/avm1/types_.py
   pypy/branch/avm/pypy/translator/avm2/avm2gen.py
   pypy/branch/avm/pypy/translator/avm2/class_.py
   pypy/branch/avm/pypy/translator/avm2/conftest.py
   pypy/branch/avm/pypy/translator/avm2/function.py
   pypy/branch/avm/pypy/translator/avm2/genavm.py
   pypy/branch/avm/pypy/translator/avm2/metavm.py
   pypy/branch/avm/pypy/translator/avm2/runtime.py
   pypy/branch/avm/pypy/translator/avm2/test/entrypoint.py
   pypy/branch/avm/pypy/translator/avm2/test/runtest.py
   pypy/branch/avm/pypy/translator/avm2/types_.py
   pypy/branch/avm/pypy/translator/driver.py
   pypy/branch/avm/pypy/translator/interactive.py
   pypy/branch/avm/pypy/translator/tool/autopath.py
Log:
More work on PyPy-AVM

Modified: pypy/branch/avm/pypy/translator/avm1/avm1.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm1/avm1.py	(original)
+++ pypy/branch/avm/pypy/translator/avm1/avm1.py	Sat Apr  3 01:46:31 2010
@@ -1,4 +1,3 @@
-
 # AVM1 = ActionScript Virtual Machine 1
 # Used for ActionScript 1 and 2
 
@@ -27,28 +26,28 @@
                _global="preload_global")
 
 class Action(object):
-    
+
     ACTION_NAME = "NotImplemented"
     ACTION_ID = 0x00
 
     offset = 0
     label_name = ""
-    
+
     def serialize(self):
         inner_data = self.gen_data()
         outer_data = self.gen_outer_data()
         header = struct.pack("<BH", self.ACTION_ID, len(inner_data))
         return header + inner_data + outer_data
-    
+
     def __len__(self):
         return 6 + len(self.gen_data()) + len(self.gen_outer_data())
-    
+
     def gen_data(self):
         return ""
 
     def gen_outer_data(self):
         return ""
-    
+
     def get_block_props_early(self, block):
         pass
 
@@ -82,7 +81,7 @@
             return ""
         else:
             return super(ActionConstantPool, self).serialize()
-    
+
     def gen_data(self):
         return struct.pack("H", len(self.pool)) + "\0".join(self.pool) + "\0"
 
@@ -91,7 +90,7 @@
     AUTO_LABEL_TEMPLATE = "label%d"
     MAX_REGISTERS = 4
     FUNCTION_TYPE = 0
-    
+
     def __init__(self, toplevel, insert_end=False):
         if toplevel:
             self.constants = toplevel.constants
@@ -99,18 +98,18 @@
         else:
             self.constants = ActionConstantPool()
             self.registers = []
-        
+
         self.code = ""
         self._sealed = False
         self.insert_end = insert_end
-        
+
         self.labels = {}
         self.branch_blocks = []
         self.actions = []
-        
+
         self.current_offset = 0
         self.label_count = 0
-    
+
     def get_free_register(self):
         if None in self.registers:
             return self.registers.index(None)
@@ -128,15 +127,15 @@
             index = self.get_free_register()
         self.registers[index] = value
         return index
-    
+
     def find_register(self, value):
         if value in self.registers:
             return self.registers.index(value)
         return -1
-    
+
     def free_register(self, index):
         self.registers[index] = None
-    
+
     def __len__(self):
         return self.current_offset + (2 if self.insert_end else 0)
 
@@ -147,17 +146,17 @@
     @property
     def sealed(self):
         return self._sealed
-    
+
     def add_action(self, action):
         if self._sealed:
             raise SealedBlockError("Block is sealed. Cannot add new actions")
 
         assert isinstance(action, Action)
-        
+
         self.code = "" # Dirty the code.
         action.offset = self.current_offset
         action.get_block_props_early(self)
-        
+
         # Do some early optimizations. Combine two pushes into one.
         if len(self.actions) > 0 and action.ACTION_NAME == "ActionPush" and self.actions[-1].ACTION_NAME == "ActionPush":
             old_action = self.actions[-1]
@@ -171,13 +170,13 @@
             self.actions.pop()
             self.current_offset -= 1 # len(ShortAction) is 1
             return None
-            
+
         if not isinstance(action, Block): # Don't add block length until we've finalized.
             self.current_offset += len(action)
-        
+
         self.actions.append(action)
         return action
-    
+
     def serialize(self):
         if not self._sealed:
             raise SealedBlockError("Block must be sealed before it can be serialized")
@@ -201,7 +200,7 @@
         name = Block.AUTO_LABEL_TEMPLATE % self.label_count
         self.labels[name] = -1
         return name
-        
+
     def set_label_here(self, name):
         self.labels[name] = self.current_offset
 
@@ -245,7 +244,7 @@
         self.function_name = name
         self.params = parameters
         self.preload_register_count = 1 # Start at 1.
-        
+
         # Flags
         self.registers        = [None]
         self.preload_parent   = False
@@ -261,31 +260,31 @@
 
         for name in parameters:
             self.registers.append(name)
-        
+
     def eval_flags(self):
-        
+
         # According to the docs, this is the order of register allocation.
         if self.preload_this and "this" not in self.registers:
             self.suppress_this = False
             self.registers.insert(1, "this")
-            
+
         if self.preload_args and "arguments" not in self.registers:
             self.suppress_args = False
             self.registers.insert(2, "arguments")
-            
+
         if self.preload_super and "super" not in self.registers:
             self.suppress_super = False
             self.registers.insert(3, "super")
-            
+
         if self.preload_root and "_root" not in self.registers:
             self.registers.insert(4, "_root")
-            
+
         if self.preload_parent and "_parent" not in self.registers:
             self.registers.insert(5, "_parent")
-        
+
         if self.preload_global and "_global" not in self.registers:
             self.registers.insert(6, "_global")
-        
+
     def gen_data(self):
 
         bits = BitStream()
@@ -299,15 +298,15 @@
         bits.write_bit(self.preload_this)
         bits.zero_fill(7) # skip over 7 Reserved bits
         bits.write_bit(self.preload_global)
-        
+
         self.block_data = Block.serialize(self)
         bytes = [self.function_name, "\0",
                  struct.pack("HB", len(self.params), len(self.registers)),
                  bits.serialize()]
-        
+
         for name in self.params:
             bytes += [chr(self.registers.index(name)), name, "\0"]
-        
+
         bytes += [struct.pack("H", len(self.block_data))]
         return "".join(bytes)
 
@@ -417,11 +416,11 @@
     ACTION_ID = 0x96
 
     USE_CONSTANTS = False
-    
+
     def __init__(self, *args):
         self.values = []
         self.add_element(*args)
-    
+
     def add_element(self, element):
         if hasattr(element, "__iter__") and not isinstance(element, (basestring, tuple)):
             for t in element:
@@ -431,14 +430,14 @@
                 element = (None, element)
             assert isinstance(element, tuple)
             self.values.append(element)
-        
+
     def get_block_props_early(self, block):
         if not ActionPush.USE_CONSTANTS: return
         for index, (value, type) in enumerate(self.values):
             if type == STRING:
                 constant_index = block.constants.add_constant(value)
                 self.values[index] = (constant_index, CONSTANT8 if constant_index < 256 else CONSTANT16)
-    
+
     def gen_data(self):
         bytes = []
         for value, type in self.values:
@@ -476,7 +475,7 @@
     def __init__(self, catch_object, try_block=None, catch_block=None, finally_block=None):
 
         self.catch_object = catch_object
-        
+
         self.try_block = try_block or Block()
         self.catch_block = catch_block or Block()
         self.finally_block = finally_block or Block()
@@ -513,7 +512,7 @@
 
     def gen_data(self):
         return struct.pack("HB", self.index, self.skip_count)
-    
+
 class ActionWaitForFrame2(Action):
     ACTION_NAME = "ActionWaitForFrame2"
     ACTION_ID = 0x8d
@@ -527,10 +526,10 @@
 class ActionWith(Action):
     ACTION_NAME = "ActionWith"
     ACTION_ID = 0x94
-    
+
     def __init__(self, with_block):
         self.block = with_block or Block()
-    
+
     def gen_data(self):
         return struct.pack("H", len(self.block)) + self.block.serialize()
 
@@ -541,13 +540,12 @@
     return ''.join('_' + c.lower() if c.isupper() else c for c in name)[1:]
 
 def make_short_action(value, name, push_count=0):
-    
     def __len__(self):
         return 1 # 1 (Action ID)
-    
+
     def serialize(self):
         return chr(self.ACTION_ID)
-    
+
     act = type(name, (Action,), dict(ACTION_ID=value, ACTION_NAME=name, push_count=push_count,
                                      __len__=__len__, serialize=serialize))
 

Modified: pypy/branch/avm/pypy/translator/avm1/avm1gen.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm1/avm1gen.py	(original)
+++ pypy/branch/avm/pypy/translator/avm1/avm1gen.py	Sat Apr  3 01:46:31 2010
@@ -50,8 +50,17 @@
             
         super(PyPyAVM1Gen, self).load(v, *args)
 
-
     def new(self, TYPE):
         if isinstance(TYPE, ootype.List):
             self.oonewarray(None)
-    
+
+    def push_primitive_constant(self, TYPE, value):
+        if TYPE is ootype.Void:
+            self.push_null()
+        elif TYPE is ootype.String:
+            if value._str is None:
+                self.push_null()
+            else:
+                self.push_const(value._str)
+        else:
+            self.push_const(value)

Modified: pypy/branch/avm/pypy/translator/avm1/types_.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm1/types_.py	(original)
+++ pypy/branch/avm/pypy/translator/avm1/types_.py	Sat Apr  3 01:46:31 2010
@@ -1,20 +1,17 @@
 
-from pypy.translator.avm import avm1
 from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
 from pypy.rpython.ootypesystem import ootype
 from pypy.rpython.lltypesystem import lltype
 
+from mech.fusion.avm1 import types_, actions
+
 _pytype_to_avm1 = {
-    str:         avm1.STRING,
-    unicode:     avm1.STRING,
-    int:         avm1.INTEGER,
-    long:        avm1.INTEGER,
-    r_longlong:  avm1.INTEGER,
-    r_ulonglong: avm1.INTEGER,
-    bool:        avm1.BOOLEAN,
-    float:       avm1.DOUBLE,
+    r_longlong:  types_.INTEGER,
+    r_ulonglong: types_.INTEGER,
 }
 
+_pytype_to_avm1.update(types_._pytype_to_avm1)
+
 def pytype_to_avm1(value):
     return (value, _pytype_to_avm1[type(value)])
 

Modified: pypy/branch/avm/pypy/translator/avm2/avm2gen.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/avm2gen.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/avm2gen.py	Sat Apr  3 01:46:31 2010
@@ -1,4 +1,3 @@
-
 """ backend generator routines
 """
 
@@ -14,32 +13,19 @@
 from pypy.translator.oosupport.constant import push_constant
 from pypy.translator.oosupport.function import render_sub_op
 
-
 from itertools import chain
 
 class PyPyAvm2ilasm(avm2gen.Avm2ilasm, Generator):
-
-    def __init__(self, db, abc):
-        super(PyPyAvm2ilasm, self).__init__(abc)
+    def __init__(self, db, abc, optimize=False):
+        super(PyPyAvm2ilasm, self).__init__(abc, optimize=optimize)
         self.db  = db
         self.cts = db.genoo.TypeSystem(db)
 
     def _get_type(self, TYPE):
-        return self.cts.lltype_to_cts(TYPE)
-
-    def _get_class_context(self, name, DICT):
-        class_desc = query.get_class_desc(name)
-        if class_desc:
-            BaseType = class_desc.BaseType
-            if '.' in BaseType:
-                ns, name = class_desc.BaseType.rsplit('.', 1)
-            else:
-                ns, name = '', BaseType
-            class_desc.super_name = constants.packagedQName(ns, name)
-            class_desc.name       = constants.packagedQName(class_desc.Package, class_desc.ShortName)
-            return class_desc
-        else:
-            return super(PyPyAvm2ilasm, self).get_class_context(name, DICT)
+        t = self.cts.lltype_to_cts(TYPE)
+        if t:
+            return t.multiname()
+        return super(PyPyAvm2ilasm, self)._get_type(TYPE)
 
     def load(self, v, *args):
         if isinstance(v, flowmodel.Variable):
@@ -57,29 +43,21 @@
         for e in args:
             self.load(e)
 
-    # def prepare_call_oostring(self, OOTYPE):
-    #     self.I(instructions.findpropstrict(types._str_qname))
-    
-    # def call_oostring(self, OOTYPE):
-    #     self.I(instructions.callproperty(types._str_qname, 1))
-        
-    # call_oounicode = call_oostring
-    # prepare_call_oounicode = prepare_call_oostring
-    
     def oonewarray(self, TYPE, length=1):
         self.load(types.vec_qname)
         self.load(self.cts.lltype_to_cts(TYPE.ITEM))
         self.I(instructions.applytype(1))
         self.load(length)
         self.I(instructions.construct(1))
-        self.I(instructions.coerce(self.cts.lltype_to_cts(TYPE).multiname()))
-    
+        self.I(instructions.coerce(self.cts.lltype_to_cts(TYPE)))
+
     def push_primitive_constant(self, TYPE, value):
         if TYPE is ootype.Void:
             self.push_null()
         elif TYPE is ootype.String:
             if value._str is None:
                 self.push_null()
+                self.downcast(types.types.string)
             else:
                 self.push_const(value._str)
         else:
@@ -87,7 +65,7 @@
 
     def new(self, TYPE):
         # XXX: assume no args for now
-        t = self.cts.lltype_to_cts(TYPE).multiname()
+        t = self._get_type(TYPE)
         self.emit('findpropstrict', t)
         self.emit('constructprop', t, 0)
 
@@ -102,23 +80,20 @@
         self.I(instructions.getproperty(constants.MultinameL(
                     constants.PROP_NAMESPACE_SET)))
 
-    def array_length(self):
-        self.I(instructions.getproperty(constants.QName("length")))
-    
-    def call_graph(self, graph, func_name=None):
+    def call_graph(self, graph, args=[]):
         """
         Call a graph.
         """
-        if func_name is None:
-            self.db.pending_function(graph)
-        func_name = func_name or graph.name
+        self.db.pending_function(graph)
         namespace = getattr(graph.func, '_namespace_', None)
+        numargs = len(args)
         if namespace:
-            qname = constants.packagedQName(namespace, func_name)
+            qname = constants.packagedQName(namespace, graph.name)
         else:
-            qname = constants.QName(func_name)
+            qname = constants.QName(graph.name)
         self.emit('findpropstrict', qname)
-        self.emit('callproperty', qname)
+        self.load(*args)
+        self.emit('callproperty', qname, numargs)
 
     def store(self, v):
         """
@@ -133,9 +108,3 @@
         self.push_var(v.name)
 
     push_arg = push_local
-
-    def new(self, TYPE):
-        # XXX: assume no args for now
-        TYPE = self._get_type(TYPE)
-        self.emit('findpropstrict', TYPE)
-        self.emit('constructprop', TYPE, 0)

Modified: pypy/branch/avm/pypy/translator/avm2/class_.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/class_.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/class_.py	Sat Apr  3 01:46:31 2010
@@ -2,7 +2,7 @@
 from pypy.translator.cli.node import Node
 from pypy.translator.oosupport.constant import push_constant
 
-from mech.fusion.avm2 import constants as c, traits
+from mech.fusion.avm2 import constants, traits
 from pypy.translator.avm2 import types_ as types
 
 try:
@@ -45,12 +45,12 @@
     def get_base_class(self):
         base_class = self.INSTANCE._superclass
         if self.INSTANCE is self.db.genoo.EXCEPTION:
-            return c.QName("Error")
+            return constants.QName("Error")
         if self.is_root(base_class):
-            return c.QName("Object")
+            return constants.QName("Object")
         else:
             ns, name = self.db.class_name(base_class).rsplit('::', 1)
-            return c.packagedQName(ns, name)
+            return constants.packagedQName(ns, name)
 
     def is_abstract(self):
         return False # XXX
@@ -80,14 +80,13 @@
             return
 
         self.ilasm = ilasm
-        self.gen = CLIBaseGenerator(self.db, ilasm)
 
-        ilasm.begin_class(c.packagedQName(self.namespace, self.name), self.get_base_class())
+        ilasm.begin_class(constants.packagedQName(self.namespace, self.name), self.get_base_class())
         for f_name, (f_type, f_default) in self.INSTANCE._fields.iteritems():
             cts_type = self.cts.lltype_to_cts(f_type)
             f_name = self.cts.escape_name(f_name)
             if cts_type != types.types.void:
-                ilasm.context.add_instance_trait(traits.AbcSlotTrait(c.QName(f_name), cts_type.multiname()))
+                ilasm.context.add_instance_trait(traits.AbcSlotTrait(constants.QName(f_name), cts_type.multiname()))
 
         self._ctor()
         self._toString()
@@ -108,7 +107,6 @@
                 while context:
                     if m_name in context._methods:
                         f.override = True
-                        print "Overriding", m_name
                         break
                     context = context._superclass
 
@@ -121,16 +119,16 @@
                            if ARG is not ootype.Void]
                 returntype = self.cts.lltype_to_cts(METH.RESULT)
                 ilasm.begin_method(m_name, arglist, returntype)
-                ilasm.emit('findpropstrict', c.QName("Error"))
+                ilasm.emit('findpropstrict', constants.QName("Error"))
                 ilasm.push_const("Abstract method %s::%s called" % (self.name, m_name))
-                ilasm.emit('constructprop', c.QName("Error"), 1)
-                ilasm.emit('throw')
+                ilasm.emit('constructprop', constants.QName("Error"), 1)
+                ilasm.throw()
                 ilasm.exit_context()
 
         ilasm.exit_context()
     
     def _ctor(self):
-        self.ilasm.context.make_iinit()
+        self.ilasm.begin_constructor()
         # set default values for fields
         default_values = self.INSTANCE._fields.copy()
         default_values.update(self.INSTANCE._overridden_defaults)
@@ -144,9 +142,8 @@
                 self.ilasm.push_this()
                 push_constant(self.db, F_TYPE, f_default, self.gen)
                 # class_name = self.db.class_name(INSTANCE_DEF)
-                self.ilasm.emit('setproperty', c.QName(f_name))
-
-        self.ilasm.exit_context()
+                self.ilasm.set_field(f_name)
+        self.ilasm.end_constructor()
 
     def _toString(self):
         if self.is_root(self.INSTANCE._superclass):
@@ -157,6 +154,5 @@
         wrapper = "Exception" if self.exception else "Instance"
         self.ilasm.begin_method('toString', [], types.types.string, override=override)
         self.ilasm.load("%sWrapper('%s')" % (wrapper, self.name))
-        self.ilasm.emit('returnvalue')
-        self.ilasm.exit_context()
-
+        self.ilasm.return_value()
+        self.ilasm.end_method()

Modified: pypy/branch/avm/pypy/translator/avm2/conftest.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/conftest.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/conftest.py	Sat Apr  3 01:46:31 2010
@@ -1,6 +1,8 @@
 def pytest_addoption(parser):
     group = parser.getgroup("pypy-tamarin options")
     group.addoption('--swf', action="store_const", const="swf", dest="tamtarget", default="swf",
-            help="generate a swf and abc and use a browsertest to run")
+                    help="generate a .swf and .abc and use a browsertest and Flash Player to run")
     group.addoption('--tamarin', action="store_const", const="tamarin", dest="tamtarget",
-                    help="generate an abc that uses tamarin")
+                    help="generate an abc that uses Tamarin")
+    group.addoption('--no-mf-optimize', action="store_false", default=True, dest="mf_optim",
+                    help="don't do simple MF optimizations")

Modified: pypy/branch/avm/pypy/translator/avm2/function.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/function.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/function.py	Sat Apr  3 01:46:31 2010
@@ -1,3 +1,4 @@
+
 from functools import partial
 
 from pypy.objspace.flow import model as flowmodel
@@ -5,19 +6,18 @@
 from pypy.rpython.lltypesystem.lltype import Void
 from pypy.translator.oosupport.function import Function as OOFunction
 from pypy.translator.cli.node import Node
-from pypy.translator.avm2 import types_ as types
 from mech.fusion.avm2 import constants
 
 class Function(OOFunction, Node):
-    
+
     auto_propagate_exceptions = True
 
-    def __init__(self, *args, **kwargs):
-        OOFunction.__init__(self, *args, **kwargs)
-        
+    def __init__(self, db, graph, name=None, is_method=False, is_entrypoint=False):
+        OOFunction.__init__(self, db, graph, name, is_method, is_entrypoint)
+
         if hasattr(self.db.genoo, 'exceptiontransformer'):
             self.auto_propagate_exceptions = False
-        
+
         namespace = getattr(self.graph.func, '_namespace_', None)
         if namespace:
             if '.' in namespace:
@@ -28,13 +28,13 @@
         else:
             self.namespace = None
             self.classname = None
-        
+
         self.override = False
-        
+
     def _create_generator(self, ilasm):
         ilasm.db = self.db
         return ilasm
-    
+
     def record_ll_meta_exc(self, ll_meta_exc):
         # record the type only if it doesn't belong to a native_class
         ll_exc = ll_meta_exc._INSTANCE
@@ -50,21 +50,21 @@
 
         if self.is_method:
             self.args = self.args[1:]
-        
+
         returntype, returnvar = self.cts.llvar_to_cts(self.graph.getreturnvar())
 
         if self.classname:
             self.generator.begin_class(constants.packagedQName(self.namespace, self.classname))
-        
+
         self.generator.begin_method(self.name, self.args, returntype, static=not self.is_method, override=self.override)
-        
+
+        self.declare_locals()
+
     def end_render(self):
-        # if self.generator.scope.islabel:
-        #     self.generator.exit_scope()
         if self.classname:
             self.generator.exit_context()
         self.generator.exit_context()
-        
+
     def render_return_block(self, block):
         return_var = block.inputargs[0]
         if return_var.concretetype is Void:
@@ -76,6 +76,11 @@
     def set_label(self, label):
         return self.generator.set_label(label)
 
+    def declare_locals(self):
+        for TYPE, name in set(self.locals):
+            TYPE.load_default(self.generator)
+            self.generator.store_var(name)
+
     def _trace_enabled(self):
         return True
 
@@ -88,38 +93,39 @@
     def _render_op(self, op):
         print "Rendering op:", op
         super(Function, self)._render_op(op)
-    
-    def _setup_link(self, link):
-        target = link.target
-        linkvars = []
-        for to_load, to_store in zip(link.args, target.inputargs):
-            if isinstance(to_load, flowmodel.Variable) and to_load.name == to_store.name:
-                continue
-            if to_load.concretetype is ootype.Void:
-                continue
-            linkvars.append((to_load, to_store))
-        
-        # after SSI_to_SSA it can happen to have to_load = [a, b] and
-        # to_store = [b, c].  If we store each variable sequentially,
-        # 'b' would be overwritten before being read.  To solve, we
-        # first load all the values on the stack, then store in the
-        # appropriate places.
-
-        if self._trace_enabled():
-            self._trace('link', writeline=True)
-            for to_load, to_store in linkvars:
-                self._trace_value('%s <-- %s' % (to_store, to_load), to_load)
-            self._trace('', writeline=True)
-        
-        for to_load, to_store in linkvars:
-            self.generator.load(to_load)
-            self.generator.store(to_store)
 
-    
+    ## def _setup_link(self, link):
+    ##     target = link.target
+    ##     linkvars = []
+    ##     for to_load, to_store in zip(link.args, target.inputargs):
+    ##         if isinstance(to_load, flowmodel.Variable) and to_load.name == to_store.name:
+    ##             continue
+    ##         if to_load.concretetype is ootype.Void:
+    ##             continue
+    ##         linkvars.append((to_load, to_store))
+
+    ##     # after SSI_to_SSA it can happen to have to_load = [a, b] and
+    ##     # to_store = [b, c].  If we store each variable sequentially,
+    ##     # 'b' would be overwritten before being read.  To solve, we
+    ##     # first load all the values on the stack, then store in the
+    ##     # appropriate places.
+
+    ##     if self._trace_enabled():
+    ##         self._trace('link', writeline=True)
+    ##         for to_load, to_store in linkvars:
+    ##             self._trace_value('%s <-- %s' % (to_store, to_load), to_load)
+    ##         self._trace('', writeline=True)
+
+    ##     for to_load, to_store in linkvars:
+    ##         self.generator.load(to_load)
+
+    ##     for to_load, to_store in reversed(linkvars):
+    ##         self.generator.store(to_store)
+
     def begin_try(self, cond):
         if cond:
             self.ilasm.begin_try()
-    
+
     def end_try(self, target_label, cond):
         if cond:
             self.ilasm.end_try()

Modified: pypy/branch/avm/pypy/translator/avm2/genavm.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/genavm.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/genavm.py	Sat Apr  3 01:46:31 2010
@@ -1,4 +1,3 @@
-
 import py
 from mech.fusion.avm2.abc_ import AbcFile
 
@@ -11,7 +10,7 @@
 from pypy.translator.avm2.types_ import Avm2TypeSystem
 
 class GenAVM2(GenOO):
-    
+
     opcodes    = opcodes
     Function   = TamarinFunction
     Database   = LowLevelDatabase
@@ -24,7 +23,7 @@
     RecordConst   = Avm2RecordConst
     ListConst     = Avm2ArrayListConst
     ArrayConst    = Avm2ArrayListConst
-    
+
     def __init__(self, tmpdir, translator, entrypoint, config=None, exctrans=False):
         GenOO.__init__(self, tmpdir, translator, entrypoint, config, exctrans)
         self.const_stat = str(tmpdir.join('const_stat'))
@@ -35,10 +34,10 @@
         clsdef = bk.getuniqueclassdef(Exception)
         ll_Exception = rtyper.exceptiondata.get_standard_ll_exc_instance(rtyper, clsdef)
         self.EXCEPTION = ll_Exception._inst._TYPE
-    
+
     def create_assembler(self):
         self.abc = AbcFile()
-        return PyPyAvm2ilasm(self.db, self.abc)
+        return PyPyAvm2ilasm(self.db, self.abc, True)
 
     def generate_source(self):
         if self.ilasm is None:
@@ -50,7 +49,3 @@
 
     def serialize_abc(self):
         return self.abc.serialize()
-
-    # Don't do treebuilding stuff
-    # def stack_optimization(self):
-    #     pass

Added: pypy/branch/avm/pypy/translator/avm2/library.py
==============================================================================
--- (empty file)
+++ pypy/branch/avm/pypy/translator/avm2/library.py	Sat Apr  3 01:46:31 2010
@@ -0,0 +1,80 @@
+
+from pypy.rpython.ootypesystem import ootype
+
+from mech.fusion.avm2.constants import QName, packagedQName, TYPE_MULTINAME_TypeName
+from mech.fusion.avm2.query import ClassDesc
+from mech.fusion.avm2.library import Library
+from mech.fusion.avm2.playerglobal.flash.utils import Vector
+
+from pypy.translator.avm2.types_ import vec_qname
+
+## Monkey Patching!
+
+ClassDesc._nativeclass = None
+
+class PyPyLibrary(Library):
+    def resolve_class(self, TYPE):
+        if self.has_type(TYPE):
+            return self.get_type(TYPE)
+        if playerglobal_lib.has_type(TYPE):
+            return self.get_type(TYPE)
+        if TYPE.KIND == TYPE_MULTINAME_TypeName and TYPE.name == vec_qname:
+            assert len(TYPE.types) == 1
+            return Vector[TYPE.types[0]]
+        if getattr(TYPE, "multiname", None):
+            return TYPE.multiname()
+
+    def convert_classdesc(self, classdesc):
+        resolve = self.resolve_class
+        from pypy.translator.avm2.runtime import NativeClass, NativeInstance
+        from pypy.translator.avm2.runtime import _overloaded_static_meth, _static_meth
+
+        if classdesc._nativeclass is not None:
+            return classdesc._nativeclass
+
+        TYPE = NativeInstance(classdesc.Package, classdesc.ShortName, None, {}, {})
+        Class = NativeClass(TYPE, {}, {})
+        classdesc._nativeclass = Class
+        if classdesc.FullName == QName('Object'):
+            TYPE._set_superclass(ootype.ROOT)
+        else:
+            BASETYPE = resolve(classdesc.BaseType)
+            TYPE._set_superclass(BASETYPE)
+
+        TYPE._isArray = classdesc.IsArray
+        if classdesc.IsArray:
+            TYPE._ELEMENT = resolve(classdesc.ElementType)
+
+        # add both static and instance methods, and static fields
+        static_meths = self.group_methods(classdesc.StaticMethods,
+            _overloaded_static_meth, _static_meth, ootype.StaticMethod)
+        meths = self.group_methods(classdesc.Methods, ootype.overload,
+                              ootype.meth, ootype.Meth)
+        Class._add_methods(static_meths)
+        Class._add_static_fields(dict((name,
+            resolve(t)) for name, t in classdesc.StaticFields]))
+        Class._add_static_fields(dict((name,
+            resolve(t)) for name, t, g, s in classdesc.StaticProperties))
+        TYPE._add_methods(meths)
+        TYPE._add_fields(dict((name, resolve(t)) for name, t in classdesc.Fields))
+        TYPE._add_fields(dict((name, resolve(t)) for name, t, g, s in classdesc.Properties))
+        return Class
+
+    def group_methods(self, methods, overload, meth, Meth):
+        from pypy.translator.avm2.runtime import OverloadingResolver
+        groups = {}
+        for name, args, result, AS3 in methods:
+            groups[name] = args, result, AS3
+
+        res = {}
+        attrs = dict(resolver=OverloadingResolver)
+        for name, methlist in groups.iteritems():
+            meths = [meth(Meth([self.resolve_class(arg) for arg in args],
+                          self.resolve_class(result))) for (args, result) in methlist]
+            res[name] = overload(*meths, **attrs)
+        return res
+
+from mech.fusion.avm2.library import get_playerglobal
+
+playerglobal_lib = get_playerglobal(Library=PyPyLibrary)
+playerglobal_lib.install_global(__name__.rpartition(".")[0]+".playerglobal")

Modified: pypy/branch/avm/pypy/translator/avm2/metavm.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/metavm.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/metavm.py	Sat Apr  3 01:46:31 2010
@@ -1,7 +1,7 @@
 from pypy.rpython.ootypesystem import ootype
-from pypy.translator.oosupport.metavm import MicroInstruction, \
-     PushAllArgs, StoreResult, GetField, SetField, DownCast
-from pypy.translator.oosupport.metavm import _Call as _OOCall
+from pypy.translator.oosupport.metavm import MicroInstruction, PushAllArgs, \
+     StoreResult, GetField, SetField, DownCast, _Call as _OOCall, \
+     get_primitive_name
 from pypy.translator.avm2.runtime import _static_meth, NativeInstance
 from pypy.translator.avm2 import types_ as types
 from mech.fusion.avm2 import constants
@@ -16,13 +16,12 @@
     return ret_type, arg_types
 
 class _Call(_OOCall):
-    
     def render(self, generator, op):
         callee = op.args[0].value
         if isinstance(callee, _static_meth):
             self._render_static_function(generator, callee, op.args)
         else:
-            _OOCall.render(self, generator, op)
+            generator.call_graph(op.args[0].value.graph, op.args[1:])
 
     def _render_static_function(self, generator, funcdesc, args):
         import pdb; pdb.set_trace()
@@ -43,6 +42,18 @@
 
 
 class _CallMethod(_Call):
+    DISPATCH = {
+        ootype.Array : {
+            "ll_setitem_fast": lambda gen: gen.array_setitem(),
+            "ll_getitem_fast": lambda gen: gen.array_getitem(),
+            "ll_length": lambda gen: gen.get_field("length", types.types.int),
+        },
+        ootype.AbstractString : {
+            "ll_append": lambda gen: gen.emit('add'),
+            "ll_stritem_nonneg": lambda gen: gen.call_method("charAt", 1, types.types.string),
+            "ll_strlen": lambda gen: gen.get_field("length", types.types.int),
+        },
+    }
     def render(self, generator, op):
         method = op.args[0]
         self._render_method(generator, method.value, op.args[1:])
@@ -55,22 +66,10 @@
         else:
             generator.load(*args)
 
-        if isinstance(this.concretetype, ootype.Array) and this.concretetype.ITEM is not ootype.Void:
-            if method_name == "ll_setitem_fast":
-                generator.array_setitem()
-            elif method_name == "ll_getitem_fast":
-                generator.array_getitem()
-            elif method_name == "ll_length":
-                generator.array_length()
-            else:
-                assert False
-        elif isinstance(this.concretetype, ootype.AbstractString):
-            if method_name == "ll_append":
-                generator.emit('add')
-            elif method_name == "ll_stritem_nonneg":
-                generator.call_method("charAt", 1)
-            elif method_name == "ll_strlen":
-                generator.get_field("length")
+        for TYPE, D in self.DISPATCH.iteritems():
+            if isinstance(this.concretetype, TYPE):
+                D[method_name](generator)
+                break
         else:
             generator.call_method(method_name, len(args)-1)
 

Modified: pypy/branch/avm/pypy/translator/avm2/runtime.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/runtime.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/runtime.py	Sat Apr  3 01:46:31 2010
@@ -14,7 +14,6 @@
 from pypy.rpython.ootypesystem.rootype import OOInstanceRepr
 from pypy.rpython.ootypesystem import ootype
 from pypy.rpython.ootypesystem.ootype import Meth, StaticMethod
-# from pypy.translator.avm2 import constants
 
 ## Annotation model
 
@@ -293,25 +292,6 @@
         meth = self._static_methods[meth_name]
         return meth._resolver.annotate(args_s)
 
-    # def _load_class(self):
-    #     names = self._INSTANCE._namespace.split('.')
-    #     names.append(self._INSTANCE._classname)
-    #     obj = PythonNet
-    #     for name in names:
-    #         obj = getattr(obj, name)
-    #     self._PythonNet_class = obj
-
-    # def __getattr__(self, attr):
-    #     if attr in self._static_methods or attr in self._static_fields:
-    #         self._load_class()
-    #         return getattr(self._PythonNet_class, attr)
-    #     else:
-    #         raise AttributeError, attr
-
-    # def __call__(self, *args):
-    #     self._load_class()
-    #     return self._PythonNet_class(*args)
-
 
 class Entry(ExtRegistryEntry):
     _type_ = NativeClass
@@ -323,190 +303,6 @@
         return SomeOOInstance(self.instance._INSTANCE)
 
 
-# BOXABLE_TYPES = [ootype.Signed, ootype.Unsigned, ootype.SignedLongLong,
-#                  ootype.UnsignedLongLong, ootype.Bool, ootype.Float,
-#                  ootype.Char, ootype.String]
-
-# class BoxedSpace:
-#     objects = {}
-#     index = 0
-#     def put(cls, obj):
-#         index = cls.index
-#         cls.objects[index] = obj
-#         cls.index += 1
-#         return index
-#     put = classmethod(put)
-
-#     def get(cls, index):
-#         return cls.objects[index]
-#     get = classmethod(get)
-
-# def box(x):
-#     t = type(x)
-#     if t is int:
-#         return CLR.System.Int32(x)
-#     elif t is r_uint:
-#         return CLR.System.UInt32(x)
-#     elif t is r_longlong:
-#         return CLR.System.Int64(x)
-#     elif t is r_ulonglong:
-#         return CLR.System.UInt64(x)
-#     elif t is bool:
-#         return CLR.System.Boolean(x)
-#     elif t is float:
-#         return CLR.System.Double(x)
-#     elif t is str or t is unicode:
-#         if len(x) == 1:
-#             return CLR.System.Char(x)
-#         else:
-#             return CLR.System.String(x)
-#     elif isinstance(x, ootype._class):
-#         if hasattr(x, '_FUNC'):
-#             TYPE = x._FUNC
-#             assert isinstance(TYPE, ootype.StaticMethod)
-#             return typeof(TYPE)
-#         else:
-#             name = '%s.%s' % (x._INSTANCE._namespace, x._INSTANCE._classname)
-#             t = CLR.System.Type.GetType(name)
-#             assert t is not None
-#             return t
-#     elif isinstance(x, PythonNet.System.Object):
-#         return x
-#     elif x is None:
-#         return None
-#     else:
-#         # cast RPython instances to System.Object is trivial when
-#         # translated but not when interpreting, because Python for
-#         # .NET doesn't support passing aribrary Python objects to
-#         # .NET. To solve, we store them in the BoxedSpace, then we
-#         # return an opaque objects, which will be used by unbox to
-#         # retrieve the original RPython instance.
-#         index = BoxedSpace.put(x)
-#         res = PythonNet.pypy.test.ObjectWrapper(index)
-#         return res
-
-# def unbox(x, TYPE):
-#     if isinstance(x, PythonNet.pypy.test.ObjectWrapper):
-#         x = BoxedSpace.get(x.index)
-
-#     if isinstance(TYPE, (type, types.ClassType)):
-#         # we need to check the TYPE and return None if it fails
-#         if isinstance(x, TYPE):
-#             return x
-#         else:
-#             return None
-
-#     if isinstance(TYPE, ootype.OOType) and TYPE is not ootype.String and not isinstance(TYPE, ootype.StaticMethod):
-#         try:
-#             return ootype.enforce(TYPE, x)
-#         except TypeError:
-#             return None
-
-#     # TODO: do the typechecking also in the other cases
-
-#     # this is a workaround against a pythonnet limitation: you can't
-#     # directly get the, e.g., python int from the System.Int32 object:
-#     # a simple way to do this is to put it into an ArrayList and
-#     # retrieve the value.
-#     tmp = PythonNet.System.Collections.ArrayList()
-#     tmp.Add(x)
-#     return tmp[0]
-
-
-# class Entry(ExtRegistryEntry):
-#     _about_ = box
-
-#     def compute_result_annotation(self, x_s):
-#         can_be_None = getattr(x_s, 'can_be_None', False)
-#         return SomeOOInstance(CLR.System.Object._INSTANCE, can_be_None=can_be_None)
-
-#     def specialize_call(self, hop):
-#         v_obj, = hop.inputargs(*hop.args_r)
-
-#         hop.exception_cannot_occur()
-#         TYPE = v_obj.concretetype
-#         if (TYPE is ootype.String or isinstance(TYPE, (ootype.OOType, NativeInstance))):
-#             return hop.genop('ooupcast', [v_obj], hop.r_result.lowleveltype)
-#         else:
-#             if TYPE not in BOXABLE_TYPES:
-#                 raise TyperError, "Can't box values of type %s" % v_obj.concretetype
-#             return hop.genop('clibox', [v_obj], hop.r_result.lowleveltype)
-
-
-# class Entry(ExtRegistryEntry):
-#     _about_ = unbox
-
-#     def compute_result_annotation(self, x_s, type_s):
-#         assert isinstance(x_s, SomeOOInstance)
-#         assert isinstance(x_s.ootype, NativeInstance)
-#         assert type_s.is_constant()
-#         TYPE = type_s.const
-#         if isinstance(TYPE, (type, types.ClassType)):
-#             # it's a user-defined class, so we return SomeInstance
-#             # can_be_None == True because it can always return None, if it fails
-#             classdef = self.bookkeeper.getuniqueclassdef(TYPE)
-#             return SomeInstance(classdef, can_be_None=True)
-#         elif TYPE in BOXABLE_TYPES:
-#             return OverloadingResolver.lltype_to_annotation(TYPE)
-#         elif isinstance(TYPE, ootype.StaticMethod):
-#             return SomeOOStaticMeth(TYPE)
-#         elif isinstance(TYPE, ootype.OOType):
-#             return SomeOOInstance(TYPE)
-#         else:
-#             assert False
-            
-
-#     def specialize_call(self, hop):
-#         assert hop.args_s[1].is_constant()
-#         TYPE = hop.args_s[1].const
-#         v_obj = hop.inputarg(hop.args_r[0], arg=0)
-#         if TYPE is ootype.String or isinstance(TYPE, (type, types.ClassType)) or isinstance(TYPE, ootype.OOType):
-#             return hop.genop('oodowncast', [v_obj], hop.r_result.lowleveltype)
-#         else:
-#             c_type = hop.inputconst(ootype.Void, TYPE)
-#             return hop.genop('cliunbox', [v_obj, c_type], hop.r_result.lowleveltype)
-
-
-
-# native_exc_cache = {}
-# def NativeException(cliClass):
-#     try:
-#         return native_exc_cache[cliClass._name]
-#     except KeyError:
-#         res = _create_NativeException(cliClass)
-#         native_exc_cache[cliClass._name] = res
-#         return res
-
-# def _create_NativeException(cliClass):
-#     from pypy.translator.cli.support import getattr_ex
-#     TYPE = cliClass._INSTANCE
-#     if PythonNet.__name__ in ('CLR', 'clr'):
-#         # we are using pythonnet -- use the .NET class
-#         name = '%s.%s' % (TYPE._namespace, TYPE._classname)
-#         res = getattr_ex(PythonNet, name)
-#     else:
-#         # we are not using pythonnet -- create a fake class
-#         res = types.ClassType(TYPE._classname, (Exception,), {})
-#     res._rpython_hints = {'NATIVE_INSTANCE': TYPE}
-#     return res
-
-# def native_exc(exc):
-#     return exc
-
-# class Entry(ExtRegistryEntry):
-#     _about_ = native_exc
-
-#     def compute_result_annotation(self, exc_s):
-#         assert isinstance(exc_s, SomeInstance)
-#         cls = exc_s.classdef.classdesc.pyobj
-#         assert issubclass(cls, Exception)
-#         NATIVE_INSTANCE = cls._rpython_hints['NATIVE_INSTANCE']
-#         return SomeOOInstance(NATIVE_INSTANCE)
-
-#     def specialize_call(self, hop):
-#         v_obj, = hop.inputargs(*hop.args_r)
-#         return hop.genop('same_as', [v_obj], hop.r_result.lowleveltype)
-
 def new_array(type, length):
     return [None] * length
 
@@ -613,69 +409,69 @@
 #         return hop.genop('cli_eventhandler', [v_obj, c_methodname], hop.r_result.lowleveltype)
 
 
-def clidowncast(obj, TYPE):
-    return obj
+## def clidowncast(obj, TYPE):
+##     return obj
 
-class Entry(ExtRegistryEntry):
-    _about_ = clidowncast
-
-    def compute_result_annotation(self, s_value, s_type):
-        if isinstance(s_type.const, ootype.OOType):
-            TYPE = s_type.const
-        else:
-            Class = s_type.const
-            TYPE = Class._INSTANCE
-        assert ootype.isSubclass(TYPE, s_value.ootype)
-        return SomeOOInstance(TYPE)
+## class Entry(ExtRegistryEntry):
+##     _about_ = clidowncast
 
-    def specialize_call(self, hop):
-        assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
-        v_inst = hop.inputarg(hop.args_r[0], arg=0)
-        return hop.genop('oodowncast', [v_inst], resulttype = hop.r_result.lowleveltype)
-
-def cast_record_to_object(record):
-    T = ootype.typeOf(record)
-    assert isinstance(T, ootype.Record)
-    return ootype._view(playerglobal.Object._INSTANCE, record)
-
-def cast_object_to_record(T, obj):
-    assert isinstance(T, ootype.Record)
-    assert isinstance(obj, ootype._view)
-    assert isinstance(obj._inst, ootype._record)
-    record = obj._inst
-    assert ootype.typeOf(record) == T
-    return record
-
-class Entry(ExtRegistryEntry):
-    _about_ = cast_record_to_object
-
-    def compute_result_annotation(self, s_value):
-        T = s_value.ootype
-        assert isinstance(T, ootype.Record)
-        can_be_None = getattr(s_value, 'can_be_None', False)
-        return SomeOOInstance(playerglobal.Object._INSTANCE, can_be_None=can_be_None)
-
-    def specialize_call(self, hop):
-        assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
-        v_obj, = hop.inputargs(*hop.args_r)
-        hop.exception_cannot_occur()
-        return hop.genop('ooupcast', [v_obj], hop.r_result.lowleveltype)
-
-class Entry(ExtRegistryEntry):
-    _about_ = cast_object_to_record
-
-    def compute_result_annotation(self, s_type, s_value):
-        assert s_type.is_constant()
-        T = s_type.const
-        assert isinstance(T, ootype.Record)
-        can_be_None = getattr(s_value, 'can_be_None', False)
-        return SomeOOInstance(T, can_be_None)
-
-    def specialize_call(self, hop):
-        assert hop.args_s[0].is_constant()
-        TYPE = hop.args_s[0].const
-        v_obj = hop.inputarg(hop.args_r[1], arg=1)
-        return hop.genop('oodowncast', [v_obj], hop.r_result.lowleveltype)
+##     def compute_result_annotation(self, s_value, s_type):
+##         if isinstance(s_type.const, ootype.OOType):
+##             TYPE = s_type.const
+##         else:
+##             Class = s_type.const
+##             TYPE = Class._INSTANCE
+##         assert ootype.isSubclass(TYPE, s_value.ootype)
+##         return SomeOOInstance(TYPE)
+
+##     def specialize_call(self, hop):
+##         assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
+##         v_inst = hop.inputarg(hop.args_r[0], arg=0)
+##         return hop.genop('oodowncast', [v_inst], resulttype = hop.r_result.lowleveltype)
+
+## def cast_record_to_object(record):
+##     T = ootype.typeOf(record)
+##     assert isinstance(T, ootype.Record)
+##     return ootype._view(playerglobal.Object._INSTANCE, record)
+
+## def cast_object_to_record(T, obj):
+##     assert isinstance(T, ootype.Record)
+##     assert isinstance(obj, ootype._view)
+##     assert isinstance(obj._inst, ootype._record)
+##     record = obj._inst
+##     assert ootype.typeOf(record) == T
+##     return record
+
+## class Entry(ExtRegistryEntry):
+##     _about_ = cast_record_to_object
+
+##     def compute_result_annotation(self, s_value):
+##         T = s_value.ootype
+##         assert isinstance(T, ootype.Record)
+##         can_be_None = getattr(s_value, 'can_be_None', False)
+##         return SomeOOInstance(playerglobal.Object._INSTANCE, can_be_None=can_be_None)
+
+##     def specialize_call(self, hop):
+##         assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
+##         v_obj, = hop.inputargs(*hop.args_r)
+##         hop.exception_cannot_occur()
+##         return hop.genop('ooupcast', [v_obj], hop.r_result.lowleveltype)
+
+## class Entry(ExtRegistryEntry):
+##     _about_ = cast_object_to_record
+
+##     def compute_result_annotation(self, s_type, s_value):
+##         assert s_type.is_constant()
+##         T = s_type.const
+##         assert isinstance(T, ootype.Record)
+##         can_be_None = getattr(s_value, 'can_be_None', False)
+##         return SomeOOInstance(T, can_be_None)
+
+##     def specialize_call(self, hop):
+##         assert hop.args_s[0].is_constant()
+##         TYPE = hop.args_s[0].const
+##         v_obj = hop.inputarg(hop.args_r[1], arg=1)
+##         return hop.genop('oodowncast', [v_obj], hop.r_result.lowleveltype)
 
 #class _fieldinfo(object):
 #     def __init__(self, llvalue):

Modified: pypy/branch/avm/pypy/translator/avm2/test/entrypoint.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/test/entrypoint.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/test/entrypoint.py	Sat Apr  3 01:46:31 2010
@@ -1,5 +1,5 @@
-
 import py
+from pypy.conftest import option
 from pypy.translator.avm2.test.browsertest import browsertest
 from pypy.translator.avm2.avm2gen import PyPyAvm2ilasm
 
@@ -8,6 +8,7 @@
      DefineEditText, SymbolClass, PlaceObject2, DoABC, ShowFrame, End
 from mech.fusion.swf.records import Rect, RGBA
 
+from mech.fusion.avm2.abc_ import AbcFile
 from mech.fusion.avm2.constants import QName, packagedQName
 from mech.fusion.avm2.traits import AbcSlotTrait
 
@@ -25,8 +26,8 @@
 '''.strip() % (name,)), color=RGBA(0xFFFFFF)))
         self.swf.add_tag(PlaceObject2(1, 2, name="edittext"))
         self.abc = DoABC("PyPy Main")
-        self.actions = PyPyAvm2ilasm(gen.db, self.abc)
-        
+        self.actions = PyPyAvm2ilasm(gen.db, self.abc, option.mf_optim)
+
         self.swf.add_tag(self.abc)
         self.swf.add_tag(SymbolClass({0:"PyPyTest_EntryPoint"}))
         self.swf.add_tag(ShowFrame())
@@ -40,9 +41,6 @@
         self.actions.store_var('text')
         self.update_text()
 
-    def serialize_swf(self):
-        return self.swf.serialize()
-
     def print_var(self, prefix, varname):
         self.actions.push_const(prefix)
         self.actions.push_var(varname)
@@ -58,12 +56,12 @@
 
     def start_test_maincls(self):
         pass
-    
+
     def start_test(self):
         self.start_test_maincls()
         if self.excwrap:
             self.actions.begin_try()
-        
+
     def finish_test(self):
         # WHHEEEEEEE!
         if self.excwrap:
@@ -83,7 +81,7 @@
 
     def do_test(self):
         pass
-    
+
     def epilogue(self):
         pass
 
@@ -97,12 +95,13 @@
         f.write(self.swf.serialize())
         f.close()
         f = open("%s.flash.abc" % (self.name,), "wb")
-        f.write(self.abc.serialize())
+        f.write(AbcFile.serialize(self.abc))
         f.close()
+        
         return browsertest(self.name, self.swf)
 
     def get_edittext(self):
-        if not self.actions.HL('edittext'):        
+        if not self.actions.HL('edittext'):
             self.actions.push_this()
             self.actions.get_field('edittext')
             self.actions.store_var('edittext')
@@ -148,16 +147,17 @@
 
 class TamarinTestEntryPoint(BaseTestEntryPoint):
     def do_test(self):
+        self.finish_test()
         f = open("%s.tamarin.abc" % (self.name,), "wb")
-        f.write(self.abc.serialize())
+        f.write(AbcFile.serialize(self.abc))
         f.close()
         asdf
 
     def update_text(self):
+        self.actions.emit('findpropstrict', QName("print"))
         self.actions.push_const("\n")
-        self.actions.get_field('text')
+        self.actions.push_var('text')
         self.actions.emit('add')
-        self.actions.emit('findpropstrict', QName("print"))
         self.actions.emit('callpropvoid', QName("print"), 1)
 
     def epilogue(self):

Modified: pypy/branch/avm/pypy/translator/avm2/test/runtest.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/test/runtest.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/test/runtest.py	Sat Apr  3 01:46:31 2010
@@ -40,33 +40,25 @@
             pass
     return string
 
-def compile_function(func, name, annotation=[], graph=None, backendopt=True,
+def compile_function(func, name, annotation=[], backendopt=True,
                      exctrans=False, annotatorpolicy=None, wrapexc=False):
     olddefs = patch_os()
-    gen = _build_gen(func, annotation, graph, backendopt,
-                     exctrans, annotatorpolicy)
+    gen = _build_gen(func, annotation, backendopt, exctrans, annotatorpolicy)
     entry_point = ENTRY_POINTS[option.tamtarget](name, gen, wrapexc)
     gen.ilasm = entry_point.actions
     gen.generate_source()
     unpatch_os(olddefs) # restore original values
-    return entry_point
+    return entry_point, gen
 
-def _build_gen(func, annotation, graph=None, backendopt=True, exctrans=False,
+def _build_gen(func, annotation, backendopt=True, exctrans=False,
                annotatorpolicy=None):
-    try: 
+    try:
         func = func.im_func
-    except AttributeError: 
+    except AttributeError:
         pass
     t = TranslationContext()
-    if graph is not None:
-        graph.func = func
-        ann = t.buildannotator(policy=annotatorpolicy)
-        inputcells = [ann.typeannotation(an) for an in annotation]
-        ann.build_graph_types(graph, inputcells)
-        t.graphs.insert(0, graph)
-    else:
-        ann = t.buildannotator(policy=annotatorpolicy)
-        ann.build_types(func, annotation)
+    ann = t.buildannotator(policy=annotatorpolicy)
+    ann.build_types(func, annotation)
 
     t.buildrtyper(type_system="ootype").specialize()
     if backendopt:
@@ -76,9 +68,8 @@
     if option.view:
         t.view()
 
-    main_graph = t.graphs[0]
     tmpdir = py.path.local('.')
-    
+
     return GenAVM2(tmpdir, t, None, exctrans)
 
 class AVM2Test(BaseRtypingTest, OORtypeMixin):
@@ -88,7 +79,6 @@
         self._harness = None
 
     def _compile(self, fn, args, ann=None, backendopt=True, exctrans=False, wrapexc=False):
-        
         frame = sys._getframe()
         while frame:
             name = frame.f_code.co_name
@@ -97,10 +87,10 @@
             frame = frame.f_back
         else:
             name = "test_unknown"
-        
+
         if ann is None:
             ann = [lltype_to_annotation(typeOf(x)) for x in args]
-        
+
         self._entry_point = compile_function(fn, "%s.%s" % (type(self).__name__, name),
             ann, backendopt=backendopt, exctrans=exctrans, wrapexc=wrapexc)
         self._func = fn
@@ -117,25 +107,26 @@
 
     def _skip_llinterpreter(self, reason, skipLL=True, skipOO=True):
         pass
-    
+
     def _get_backendopt(self, backendopt):
         if backendopt is None:
             backendopt = getattr(self, 'backendopt', True) # enable it by default
         return backendopt
-    
-    def interpret(self, fn, args, annotation=None, backendopt=None, exctrans=False, wrapexc=False):
+
+    def interpret(self, fn, args, annotation=None, backendopt=None,
+                  exctrans=False, wrapexc=False):
         backendopt = self._get_backendopt(backendopt)
-        entry_point = self._compile(fn, args, annotation, backendopt=backendopt,
-                                exctrans=exctrans, wrapexc=wrapexc)
-        print entry_point
+        entry_point, gen = self._compile(fn, args, annotation,
+            backendopt, exctrans, wrapexc)
         entry_point.start_test()
-        entry_point.actions.call_function_constargs(fn.func_name, *args)
+        entry_point.actions.call_graph(gen.translator.graphs[0], args)
         result = parse_result(entry_point.do_test())
         if isinstance(result, ExceptionWrapper):
             raise result
         return result
-    
-    def interpret_raises(self, exception, fn, args, backendopt=None, exctrans=False):
+
+    def interpret_raises(self, exception, fn, args, backendopt=None,
+                         exctrans=False):
         import exceptions # needed by eval
         backendopt = self._get_backendopt(backendopt)
         try:
@@ -163,7 +154,7 @@
         return t
 
     def class_name(self, value):
-        return value.class_name.split(".")[-1] 
+        return value.class_name.split(".")[-1]
 
     def is_of_instance_type(self, val):
         return isinstance(val, InstanceWrapper)

Modified: pypy/branch/avm/pypy/translator/avm2/types_.py
==============================================================================
--- pypy/branch/avm/pypy/translator/avm2/types_.py	(original)
+++ pypy/branch/avm/pypy/translator/avm2/types_.py	Sat Apr  3 01:46:31 2010
@@ -1,5 +1,5 @@
 """
-Translate between PyPy ootypesystem and .NET Common Type System
+bTranslate between PyPy ootypesystem and .NET Common Type System
 """
 
 import exceptions
@@ -22,74 +22,75 @@
     def typename(self):
         raise NotImplementedError
 
+    def load_default(self, asm):
+        raise NotImplementedError
+
     def __str__(self):
-        return self.typename()
+        return str(self.multiname())
 
     def __hash__(self):
-        return hash(self.typename())
-    
+        return hash(self.multiname())
+
     def __eq__(self, other):
-        return isinstance(other, self.__class__) and self.typename() == other.typename()
-    
-    def __ne__(self, other):
-        return self.typename() != other.typename()
+        return isinstance(other, type(self)) and self.multiname() == other.multiname()
 
+    def __ne__(self, other):
+        return not self == other
 
 class Avm2PrimitiveType(Avm2Type):
-    def __init__(self, name):
-        self.name = name
+    def __init__(self, name, default):
+        self.name, self.default = name, default
+
+    def load_default(self, gen):
+        gen.load(self.default)
 
     def typename(self):
         return self.name
 
     def multiname(self):
         return constants.QName(self.typename())
-    
 
 class Avm2NamespacedType(Avm2Type):
     nstype = constants.TYPE_NAMESPACE_PackageNamespace
-    
     def __init__(self, name, namespace=''):
-        print "Namedspaced Type", name
         if '::' in name and namespace == '':
             self.ns, self.name = name.rsplit('::', 1)
         else:
             self.name = name
             self.ns = namespace
-    
+
     def typename(self):
         return "%s::%s" % (self.ns, self.name)
-    
-    def classname(self):
-        raise NotImplementedError
 
     def multiname(self):
         return constants.QName(self.name, constants.Namespace(self.nstype, self.ns))
 
-
 class Avm2ArrayType(Avm2Type):
-
     def __init__(self, itemtype):
-        self.itemtype = itemtype
+        self.ITEM = itemtype
+
+    def load_default(self, gen):
+        gen.oonewarray(self, 0)
+
+    def __str__(self):
+        return "%s.<%s>" % (vec_qname, constants.QName(self.ITEM))
 
     def multiname(self):
-        return constants.TypeName(vec_qname, self.itemtype.multiname())
+        return constants.TypeName(vec_qname, constants.QName(self.ITEM))
 
 T = Avm2PrimitiveType
-N = Avm2NamespacedType
+# N = Avm2NamespacedType
 class types:
-    void   =  T('void')
-    int    =  T('int')
-    uint   =  T('uint')
-    bool   =  T('Boolean')
-    float  =  T('Number')
-    string =  T('String')
-
-    # weakref = CliClassType('pypylib', 'pypy.runtime.WeakReference')
-    type   =  T('Class')
-    object =  T('Object')
+    void   =  T('void', constants.null)
+    int    =  T('int', -1)
+    uint   =  T('uint', 0)
+    bool   =  T('Boolean', False)
+    float  =  T('Number', float('nan'))
+    string =  T('String', "")
+    type   =  T('Class', constants.QName('Class'))
+    object =  T('Object', {})
     list   =  Avm2ArrayType
-    dict   =  T('Object')
+    dict   =  T('Object', {})
 #    sb     =  N('StringBuilder', 'pypy.lib')
 del T
 
@@ -104,9 +105,9 @@
     ootype.Char: types.string,
     ootype.UniChar: types.string,
     ootype.Class: types.type,
-#   ootype.String: types.string,
+    ootype.String: types.string,
 #   ootype.StringBuilder: types.sb,
-#   ootype.Unicode: types.string,
+    ootype.Unicode: types.string,
 #   ootype.UnicodeBuilder: types.sb,
 
     # maps generic types to their ordinal
@@ -114,24 +115,14 @@
     ootype.Dict.SELFTYPE_T: types.dict,
 }
 
-
-def _get_from_dict(d, key, error):
-    try:
-        return d[key]
-    except KeyError:
-        if getoption('nostop'):
-            log.WARNING(error)
-            return key
-        else:
-            assert False, error
-
 class Avm2TypeSystem(object):
-
     def __init__(self, db):
         self.db = db
 
     def lltype_to_cts(self, t):
-        if t is ootype.ROOT:
+        if isinstance(t, Avm2Type):
+            return t
+        elif t is ootype.ROOT:
             return types.object
         elif isinstance(t, lltype.Ptr) and isinstance(t.TO, lltype.OpaqueType):
             return types.object
@@ -155,16 +146,16 @@
             key_type = self.lltype_to_cts(t._KEYTYPE)
             value_type = self.lltype_to_cts(t._VALUETYPE)
             return types.dict
-        elif isinstance(t, ootype.DictItemsIterator):
-            key_type = self.lltype_to_cts(t._KEYTYPE)
-            value_type = self.lltype_to_cts(t._VALUETYPE)
-            if key_type == types.void:
-                key_type = types.int32 # placeholder
-            if value_type == types.void:
-                value_type = types.int32 # placeholder
-            return types.dict_items_iterator.specialize(key_type, value_type)
+        ## elif isinstance(t, ootype.DictItemsIterator):
+        ##     key_type = self.lltype_to_cts(t._KEYTYPE)
+        ##     value_type = self.lltype_to_cts(t._VALUETYPE)
+            ## if key_type == types.void:
+            ##     key_type = types.int32 # placeholder
+            ## if value_type == types.void:
+            ##     value_type = types.int32 # placeholder
+            ## return types.dict_items_iterator.specialize(key_type, value_type)
 
-        return _get_from_dict(_lltype_to_cts, t, 'Unknown type %s' % t)
+        return _lltype_to_cts.get(t, None)
 
     def llvar_to_cts(self, var):
         return self.lltype_to_cts(var.concretetype), var.name
@@ -176,13 +167,13 @@
         return name
 
     def graph_to_qname(self, graph):
-        func_name = self.graph.name
-        namespace = getattr(self.graph, '_namespace_', None)
+        func_name = graph.name
+        namespace = getattr(graph, '_namespace_', None)
         if namespace:
             return constants.packagedQName(namespace, func_name)
         else:
             return constants.QName(func_name)
-    
+
     # def ctor_name(self, t):
     #     return 'instance void %s::.ctor()' % self.lltype_to_cts(t)
 

Modified: pypy/branch/avm/pypy/translator/driver.py
==============================================================================
--- pypy/branch/avm/pypy/translator/driver.py	(original)
+++ pypy/branch/avm/pypy/translator/driver.py	Sat Apr  3 01:46:31 2010
@@ -9,7 +9,7 @@
 from pypy.annotation import model as annmodel
 from pypy.annotation.listdef import s_list_of_strings
 from pypy.annotation import policy as annpolicy
-from py.compat import optparse
+import optparse
 from pypy.tool.udir import udir
 from pypy.rlib.jit import DEBUG_OFF, DEBUG_DETAILED, DEBUG_PROFILE, DEBUG_STEPS
 
@@ -546,6 +546,28 @@
                                       [STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE], 
                                       "LLInterpreting")
 
+    def task_compile_tamarin(self):
+        from pypy.translator.avm2.genavm import GenAVM2
+        from pypy.translator.avm2.entrypoint import get_entrypoint
+
+        if self.entry_point is not None: # executable mode
+            entry_point_graph = self.translator.graphs[0]
+            entry_point = get_entrypoint(entry_point_graph)
+        else:
+            # library mode
+            assert self.libdef is not None
+            bk = self.translator.annotator.bookkeeper
+            entry_point = self.libdef.get_entrypoint(bk)
+
+        self.gen = GenAVM2(udir, self.translator, entry_point, config=self.config)
+        self.gen.generate_source()
+        abc = self.gen.serialize_abc()
+        f = open(entry_point.get_name() + ".abc", "wb")
+        f.write(abc)
+        f.close()
+    task_compile_tamarin = taskdef(task_compile_tamarin, ["?" + OOBACKENDOPT, OOTYPE],
+                                   'Generating ABC bytecode')
+
     def task_source_cli(self):
         from pypy.translator.cli.gencli import GenCli
         from pypy.translator.cli.entrypoint import get_entrypoint
@@ -599,14 +621,25 @@
             shutil.copy(os.path.join(usession_path, 'main.il'), dirname)
         newexename = basename
         f = file(newexename, 'w')
-        f.write("""#!/bin/bash
+        f.write(r"""#!/bin/bash
 LEDIT=`type -p ledit`
 EXE=`readlink $0`
 if [ -z $EXE ]
 then
     EXE=$0
 fi
-if  uname -s | grep -iq Cygwin ; then MONO=; else MONO=mono; fi
+if  uname -s | grep -iq Cygwin
+then 
+    MONO=
+else 
+    MONO=mono
+    # workaround for known mono buggy versions
+    VER=`mono -V | head -1 | sed s/'Mono JIT compiler version \(.*\) (.*'/'\1/'`
+    if [[ 2.1 < "$VER" && "$VER" < 2.4.3 ]]
+    then
+        MONO="mono -O=-branch"
+    fi
+fi
 $LEDIT $MONO "$(dirname $EXE)/$(basename $EXE)-data/%s" "$@" # XXX doesn't work if it's placed in PATH
 """ % main_exe_name)
         f.close()

Modified: pypy/branch/avm/pypy/translator/interactive.py
==============================================================================
--- pypy/branch/avm/pypy/translator/interactive.py	(original)
+++ pypy/branch/avm/pypy/translator/interactive.py	Sat Apr  3 01:46:31 2010
@@ -1,4 +1,4 @@
-from py.compat import optparse
+import optparse
 
 import autopath
 from pypy.translator.translator import TranslationContext
@@ -150,7 +150,13 @@
         backend = self.ensure_backend()
         getattr(self.driver, 'compile_'+backend)()
         return self.driver.c_entryp
-       
+
+    def compile_tamarin(self, argtypes=None, **kwds):
+        self.update_options(argtypes, kwds)
+        self.ensure_backend('tamarin')
+        self.driver.compile_tamarin()
+        return self.driver.c_entryp
+    
     def compile_c(self, argtypes=None, **kwds):
         self.update_options(argtypes, kwds)
         self.ensure_backend('c')

Modified: pypy/branch/avm/pypy/translator/tool/autopath.py
==============================================================================
--- pypy/branch/avm/pypy/translator/tool/autopath.py	(original)
+++ pypy/branch/avm/pypy/translator/tool/autopath.py	Sat Apr  3 01:46:31 2010
@@ -37,8 +37,7 @@
         partdir = head
         head, tail = os.path.split(head)
         if tail == part:
-            # check if "../py/__init__.py" exists
-            checkfile = os.path.join(partdir, os.pardir, 'py', '__init__.py')
+            checkfile = os.path.join(partdir, os.pardir, 'pypy', '__init__.py')
             if not os.path.exists(checkfile):
                 error = "Cannot find %r" % (os.path.normpath(checkfile),)
             break



More information about the Pypy-commit mailing list