Commits

Jean-Philippe St. Pierre  committed 13923f4

getting ready for first push to svn

  • Participants
  • Parent commits 7dd8ce1
  • Branches avm

Comments (0)

Files changed (45)

File pypy/translator/avm1/.ropeproject/config.py

+# The default ``config.py``
+
+
+def set_prefs(prefs):
+    """This function is called before opening the project"""
+
+    # Specify which files and folders to ignore in the project.
+    # Changes to ignored resources are not added to the history and
+    # VCSs.  Also they are not returned in `Project.get_files()`.
+    # Note that ``?`` and ``*`` match all characters but slashes.
+    # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
+    # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
+    # '.svn': matches 'pkg/.svn' and all of its children
+    # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
+    # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
+    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
+                                  '.hg', '.svn', '_svn', '.git']
+
+    # Specifies which files should be considered python files.  It is
+    # useful when you have scripts inside your project.  Only files
+    # ending with ``.py`` are considered to be python files by
+    # default.
+    #prefs['python_files'] = ['*.py']
+
+    # Custom source folders:  By default rope searches the project
+    # for finding source folders (folders that should be searched
+    # for finding modules).  You can add paths to that list.  Note
+    # that rope guesses project source folders correctly most of the
+    # time; use this if you have any problems.
+    # The folders should be relative to project root and use '/' for
+    # separating folders regardless of the platform rope is running on.
+    # 'src/my_source_folder' for instance.
+    #prefs.add('source_folders', 'src')
+
+    # You can extend python path for looking up modules
+    #prefs.add('python_path', '~/python/')
+
+    # Should rope save object information or not.
+    prefs['save_objectdb'] = True
+    prefs['compress_objectdb'] = False
+
+    # If `True`, rope analyzes each module when it is being saved.
+    prefs['automatic_soa'] = True
+    # The depth of calls to follow in static object analysis
+    prefs['soa_followed_calls'] = 0
+
+    # If `False` when running modules or unit tests "dynamic object
+    # analysis" is turned off.  This makes them much faster.
+    prefs['perform_doa'] = True
+
+    # Rope can check the validity of its object DB when running.
+    prefs['validate_objectdb'] = True
+
+    # How many undos to hold?
+    prefs['max_history_items'] = 32
+
+    # Shows whether to save history across sessions.
+    prefs['save_history'] = True
+    prefs['compress_history'] = False
+
+    # Set the number spaces used for indenting.  According to
+    # :PEP:`8`, it is best to use 4 spaces.  Since most of rope's
+    # unit-tests use 4 spaces it is more reliable, too.
+    prefs['indent_size'] = 4
+
+    # Builtin and c-extension modules that are allowed to be imported
+    # and inspected by rope.
+    prefs['extension_modules'] = []
+
+    # Add all standard c-extensions to extension_modules list.
+    prefs['import_dynload_stdmods'] = True
+
+    # If `True` modules with syntax errors are considered to be empty.
+    # The default value is `False`; When `False` syntax errors raise
+    # `rope.base.exceptions.ModuleSyntaxError` exception.
+    prefs['ignore_syntax_errors'] = False
+
+    # If `True`, rope ignores unresolvable imports.  Otherwise, they
+    # appear in the importing namespace.
+    prefs['ignore_bad_imports'] = False
+
+
+def project_opened(project):
+    """This function is called after opening the project"""
+    # Do whatever you like here!

File pypy/translator/avm1/.ropeproject/globalnames

+�}qUavm1q]q(UActionStringEqualsqUActionDefineLocalqUActionMultiplyqUActionCallFunctionqUActionShiftLeftqUActionSetVariableq	UActionAsciiToCharq
+UActionGetPropertyq
+ActionStopqU	ActionAndqUBranchingActionBaseqU
+ActionLessq
+ActionJumpq$UActionNewObjectq%U	Undefinedq&UActionCallMethodq'UActionMBCharToAsciiq(U
+ActionWithqPU
+ActionSwapqQU
+ActionPushqcUActionToIntegerqdUActionTypedEqualsqeU
+ActionCallqfUActionStringLessqgUActionSetMemberqhU
+ActionPlayqiU	DataTypesqjUActionStringLengthqkU

File pypy/translator/avm1/.ropeproject/history

+�]q(]q]qe.

File pypy/translator/avm1/.ropeproject/objectdb

+�}qUavm1.pyq}qUBlock.__init__qcrope.base.oi.memorydb
+ScopeInfo
+q)�q}qUinstanceqUdefinedq	hUActionDefineFunction2q
+��Uunknown�q

File pypy/translator/avm1/avm1.py

     ACTION_NAME = "ActionPush"
     ACTION_ID = 0x96
 
+    USE_CONSTANTS = False
+    
     def __init__(self, *args):
         self.values = []
         self.add_element(*args)
             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)

File pypy/translator/avm1/avm1gen.py

     
     def set_member(self):
         self.action(avm1.ActionSetMember())
-        self.pop_stack(3)
+        value, name, obj = self.pop_stack(3)
+        print "SETMEMBER: %s.%s = %r" % (obj, name, value)
         
     def get_member(self):
         self.action(avm1.ActionGetMember())
         name, obj = self.pop_stack(2)
         print "GETMEMBER:", name, obj
-        self.push_stack(Variable("%s.%s") % obj, name)
+        self.push_stack(Variable("%s.%s" % (obj, name)))
         
     def push_reg_index(self, index):
         self.action(avm1.ActionPush((index, avm1.REGISTER)))
         k = self.find_register(v)
         print k
         if k >= 0:
-            self.push_stack(v)
+            self.push_stack(Variable(v))
             self.push_reg_index(k)
         else:
             if self.in_function() == 2:
         self.pop_stack(2)
     
     def init_object(self, members={}):
-        self.push_const(*members.items())
+        self.load(members.items())
         self.push_const(len(members))
         self.action(avm1.ActionInitObject())
         self.pop_stack(self.pop_stack()[0])
         self.push_stack(ScriptObject("object"))
 
     def init_array(self, members=[]):
-        self.push_const(members)
+        self.load(members)
         self.push_const(len(members))
         self.action(avm1.ActionInitArray())
         self.pop_stack(self.pop_stack()[0])
         
     # Assumes the args and number of args and ScriptObject are on the stack.
     def call_method_n(self, func_name):
-        self.push_const(func_name)
+        self.load(func_name)
         self.action(avm1.ActionCallMethod())
         name, obj, nargs = self.pop_stack(3)
         self.pop_stack(nargs)
     # If no args are passed then it is assumed that the args and number of args are on the stack.
     def newobject_constthis(self, obj, *args):
         if len(args) > 0:
-            self.push_const(args, len(args), obj)
+            self.load(args+(len(args), obj))
         else:
-            self.push_const(obj)
+            self.load(obj)
         self.newobject()
         
     
     def newobject(self):
         self.action(avm1.ActionNewObject())
-        name, nargs = self.pop_stack()
+        name, nargs = self.pop_stack(2)
         args = self.pop_stack(nargs)
         self.push_stack(ScriptObject(name))
         
 
     def dup(self, TYPE):
         self.action(avm1.ActionDuplicate())
-        self.push_stack([self.pop_stack()] * 2)
+        self.push_stack(*[self.pop_stack()] * 2)
     
     def load(self, v):
-        print v, type(v)
         if hasattr(v, "__iter__")  and not isinstance(v, basestring):
             for i in v:
-                self.load(v)
+                self.load(i)
         elif isinstance(v, ClassName):
             if v.namespace:
                 ns = v.namespace.split('.')
 
     call_oounicode = call_oostring
 
-    # def new(self, TYPE):
-    #     pass
+    def new(self, TYPE):
+        if isinstance(TYPE, ootype.List):
+            self.oonewarray(None)
     
-    def oonewarray(self, TYPE, length):
-        self.newobject_constthis("Array", 1)
+    def oonewarray(self, TYPE, length=1):
+        self.newobject_constthis("Array", length)
     
     def push_null(self, TYPE=None):
         self.action(avm1.ActionPush(avm1.NULL))
-        self
+        self.push_stack(avm1.NULL)
 
     def push_undefined(self):
         self.action(avm1.ActionPush(avm1.UNDEFINED))
 
     def push_primitive_constant(self, TYPE, value):
         if TYPE is ootype.Void:
-            self.push_undefined()
+            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)

File pypy/translator/avm1/constant.py

 
-from pypy.translator.oosupport.constant import BaseConstantGenerator
+from pypy.translator.oosupport import constant as c
 
 CONST_OBJNAME = "PYPY_INTERNAL_CONSTANTS"
 
 # Different generators implementing different techniques for loading
 # constants (Static fields, singleton fields, etc)
 
-class AVM1ConstGenerator(BaseConstantGenerator):
+class AVM1ConstGenerator(c.BaseConstantGenerator):
     """
     AVM1 constant generator.  It implements the oosupport
     constant generator in terms of the AVM1 virtual machine.
     """
 
     def __init__(self, db):
-        BaseConstantGenerator.__init__(self, db)
+        c.BaseConstantGenerator.__init__(self, db)
         self.cts = db.genoo.TypeSystem(db)
 
-    def _begin_gen_constants(self, asmgen, all_constants):
-        self.asmgen = asmgen
-        self.asmgen.push_const(CONST_OBJNAME)
-        self.asmgen.init_object()
-        self.asmgen.store_register(CONST_OBJNAME)
-        self.asmgen.set_variable()
-        return asmgen
+    def _begin_gen_constants(self, gen, all_constants):
+        gen.push_const(CONST_OBJNAME)
+        gen.init_array()
+        gen.store_register(CONST_OBJNAME)
+        gen.set_variable()
+        return gen
 
-    def _end_gen_constants(self, a, b):
+    def _end_gen_constants(self, gen, numsteps):
+        pass
+
+    def _declare_const(self, gen, const):
+        pass
+    
+    def _close_step(self, gen, stepnum):
         pass
     
     # _________________________________________________________________
     # OOSupport interface
     
     def push_constant(self, gen, const):
-        gen.asmgen.push_var(CONST_OBJNAME)
-        gen.asmgen.push_const(const.name)
-        gen.asmgen.get_member()
+        gen.push_var(CONST_OBJNAME)
+        gen.push_const(const.name)
+        gen.get_member()
 
-    def _store_constant(self, gen, const):
-        gen.asmgen.set_static_field(CONST_OBJNAME, const.name)
+    def _create_pointers(self, gen, all_constants):
+        pass
+
+    def _initialize_data(self, gen, all_constants):
+        """ Iterates through each constant, initializing its data. """
+        # gen.add_section("Initialize Data Phase")
+        for const in all_constants:
+            # gen.add_comment("Constant: %s" % const.name)
+            const.initialize_data(self, gen)
+
+
+class AVM1ArrayListConst(c.ListConst):
+
+    NAME = 'NOT_IMPL'
+    
+    def __init__(self, db, list, count):
+        c.AbstractConst.__init__(self, db, list, count)
+        self.name = '%s__%d' % (self.NAME, count)
+
+    def create_pointer(self, gen):
+        assert False
+        
+    def initialize_data(self, constgen, gen):
+        assert not self.is_null()
+        
+        if self._do_not_initialize():
+            return
+
+        gen.push_var(CONST_OBJNAME)
+        gen.push_const(self.name)
+        gen.init_array(self.value._list)
+        gen.set_member()
+        
+        # for idx, item in enumerate(self.value._list):
+        #     gen.push_const(CONST_OBJNAME, CONST_OBJNAME)
+        #     gen.get_variable()
+        #     gen.get_variable()
+        #     gen.push_const(self.name, self.name)
+        #     gen.get_member()
+        #     gen.push_const(idx)
+        #     gen.load(item)
+        #     gen.set_member()
+        #     gen.set_member()
+
+class AVM1ArrayConst(AVM1ArrayListConst):
+    NAME = 'ARRAY'
+
+class AVM1ListConst(AVM1ArrayListConst):
+    NAME = 'LIST'
+
+class AVM1DictConst(c.DictConst):
+    def initialize_data(self, constgen, gen):
+        assert not self.is_null()
+        
+        gen.push_var(CONST_OBJNAME)
+        gen.push_const(self.name)
+        gen.init_object(self.value._dict)
+        gen.set_member()
+        
+        # for key, value in self.value._dict.iteritems():
+        #     gen.push_const(CONST_OBJNAME, CONST_OBJNAME)
+        #     gen.get_variable()
+        #     gen.get_variable()
+        #     gen.push_const(self.name, self.name)
+        #     gen.get_member()
+        #     gen.load(key)
+        #     gen.load(value)
+        #     gen.set_member()
+        #     gen.set_member()
+

File pypy/translator/avm1/database.py

         return name
 
     def class_name(self, INSTANCE):
-        if INSTANCE is ootype.ROOT:
-            return types.object.classname()
+        #if INSTANCE is ootype.ROOT:
+        #    return types.object.classname()
         try:
             NATIVE_INSTANCE = INSTANCE._hints['NATIVE_INSTANCE']
             return NATIVE_INSTANCE._name

File pypy/translator/avm1/function.py

+from functools import partial
+
+from pypy.objspace.flow import model as flowmodel
+from pypy.rpython.ootypesystem import ootype
+from pypy.rpython.lltypesystem.lltype import Void
+from pypy.translator.oosupport.function import Function as OOFunction
+from pypy.translator.avm.node import Node
+from pypy.translator.avm.avm1gen import ClassName
+
+def load_variable_hook(self, v):
+    if v.name in self.argset:
+        selftype, selfname = self.args[0]
+        if self.is_method and v.name == selfname:
+            self.generator.push_this() # special case for 'self'
+        else:
+            self.generator.push_arg(v)
+        return True
+    return False
+    
+
+class Function(OOFunction, Node):
+    
+    auto_propagate_exceptions = True
+
+    def __init__(self, *args, **kwargs):
+        OOFunction.__init__(self, *args, **kwargs)
+        
+        if hasattr(self.db.genoo, 'exceptiontransformer'):
+            self.auto_propagate_exceptions = False
+        
+        namespace = getattr(self.graph.func, '_namespace_', None)
+        if namespace:
+            if '.' in namespace:
+                self.namespace, self.classname = namespace.rsplit('.', 1)
+            else:
+                self.namespace = None
+                self.classname = namespace
+        else:
+            self.namespace = None
+            self.classname = None
+
+    def _create_generator(self, ilasm):
+        ilasm.db = self.db
+        ilasm.load_variable_hook = partial(load_variable_hook, self)
+        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
+        NATIVE_INSTANCE = ll_exc._hints.get('NATIVE_INSTANCE', None)
+        if NATIVE_INSTANCE is None:
+            OOFunction.record_ll_meta_exc(self, ll_meta_exc)
+
+    def begin_render(self):
+        self._set_args()
+        self._set_locals()
+        if self.args:
+            args = zip(*self.args)[1]
+        else:
+            args = ()
+        if self.is_method:
+            self.generator.begin_method(self.name, ClassName(self.namespace, self.classname), args[1:])
+        elif self.classname:
+            self.generator.begin_static_method(self.name, ClassName(self.namespace, self.classname), args)
+        else:
+            self.generator.begin_function(self.name, args)
+        
+    def end_render(self):
+        if self.generator.scope.islabel:
+            self.generator.exit_scope()
+        self.generator.exit_scope()
+        
+    def render_return_block(self, block):
+        print "RETURN BLOCK RENDERING"
+        return_var = block.inputargs[0]
+        if return_var.concretetype is not Void:
+            self.generator.load(return_var)
+        self.generator.return_stmt()
+
+    def set_label(self, label):
+        return self.generator.set_label(label)
+
+    # def _render_op(self, op):
+    #     #instr_list = self.db.genoo.opcodes.get(op.opname, None)
+    #     #instr_list.render(self.generator, 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_store)
+            self.generator.load(to_load)
+            self.generator.set_variable()
+
+    
+    # def begin_try(self, cond):
+    #     if cond:
+    #         self.ilasm.begin_try()
+    
+    # def end_try(self, target_label, cond):
+    #     if cond:
+    #         self.ilasm.leave(target_label)
+    #         self.ilasm.end_try()
+    #     else:
+    #         self.ilasm.branch(target_label)
+
+    # def begin_catch(self, llexitcase):
+    #     ll_meta_exc = llexitcase
+    #     ll_exc = ll_meta_exc._INSTANCE
+    #     cts_exc = self.cts.lltype_to_cts(ll_exc)
+    #     self.ilasm.begin_catch(cts_exc.classname())
+
+    # def end_catch(self, target_label):
+    #     self.ilasm.leave(target_label)
+    #     self.ilasm.end_catch()
+
+    # def render_raise_block(self, block):
+    #     exc = block.inputargs[1]
+    #     self.load(exc)
+    #     self.ilasm.opcode('throw')
+
+    # def store_exception_and_link(self, link):
+    #     if self._is_raise_block(link.target):
+    #         # the exception value is on the stack, use it as the 2nd target arg
+    #         assert len(link.args) == 2
+    #         assert len(link.target.inputargs) == 2
+    #         self.store(link.target.inputargs[1])
+    #     else:
+    #         # the exception value is on the stack, store it in the proper place
+    #         if isinstance(link.last_exception, flowmodel.Variable):
+    #             self.ilasm.opcode('dup')
+    #             self.store(link.last_exc_value)
+    #             self.ilasm.call_method(
+    #                 'class [mscorlib]System.Type object::GetType()',
+    #                 virtual=True)
+    #             self.store(link.last_exception)
+    #         else:
+    #             self.store(link.last_exc_value)
+    #         self._setup_link(link)
+
+    # def render_numeric_switch(self, block):
+    #     if block.exitswitch.concretetype in (ootype.SignedLongLong, ootype.UnsignedLongLong):
+    #         # TODO: it could be faster to check is the values fit in
+    #         # 32bit, and perform a cast in that case
+    #         self.render_numeric_switch_naive(block)
+    #         return
+
+    #     cases, min_case, max_case, default = self._collect_switch_cases(block)
+    #     is_sparse = self._is_sparse_switch(cases, min_case, max_case)
+
+    #     naive = (min_case < 0) or is_sparse
+    #     if naive:
+    #         self.render_numeric_switch_naive(block)
+    #         return
+
+    #     targets = []
+    #     for i in xrange(max_case+1):
+    #         link, lbl = cases.get(i, default)
+    #         targets.append(lbl)
+    #     self.generator.load(block.exitswitch)
+    #     self.ilasm.switch(targets)
+    #     self.render_switch_case(*default)
+    #     for link, lbl in cases.itervalues():
+    #         self.render_switch_case(link, lbl)
+
+    # def call_oostring(self, ARGTYPE):
+    #     if isinstance(ARGTYPE, ootype.Instance):
+    #         argtype = self.cts.types.object
+    #     else:
+    #         argtype = self.cts.lltype_to_cts(ARGTYPE)
+    #     self.call_signature('string [pypylib]pypy.runtime.Utils::OOString(%s, int32)' % argtype)
+
+    # def call_oounicode(self, ARGTYPE):
+    #     argtype = self.cts.lltype_to_cts(ARGTYPE)
+    #     self.call_signature('string [pypylib]pypy.runtime.Utils::OOUnicode(%s)' % argtype)
+
+    # Those parts of the generator interface that are function
+    # specific

File pypy/translator/avm1/metavm.py

             generator.load(arg)
         generator.push_const(len(args))
 
+class _CallMethod(MicroInstruction):
+    def render(self, generator, op):
+        args = op.args
+        method_name = args[0].value
+        this = args[1]
+        
+        if isinstance(this.concretetype, ootype.Array):
+            for arg in args[1:]:
+                generator.load(arg)
+            if method_name == "ll_setitem_fast":
+                generator.set_member()
+                generator.push_const(False) # Spoof a method call result
+            elif method_name == "ll_getitem_fast":
+                generator.get_member()
+            elif method_name == "ll_length":
+                generator.load("length")
+                generator.get_member()
+            else:
+                assert False
+        else:
+            if len(args) > 2:
+                for arg in args[2:]:
+                    generator.load(arg)
+                generator.push_const(len(args)-2)
+            else:
+                generator.push_const(0)
+            generator.load(this)
+            generator.call_method_n(method_name)
+
 class CallConstantMethod(MicroInstruction):
     def __init__(self, obj, func_name):
         self.obj = obj
 StoreResultEnd          = _StoreResultEnd()
 GetField                = _GetField()
 SetField                = _SetField()
+CallMethod              = _CallMethod()

File pypy/translator/avm1/opcodes.py

     'runtimenew':    [om.RuntimeNew],
     'oosetfield':    [am.SetField],
     'oogetfield':    [am.GetField],
-#    'oosend':        am.CallMethod
+    'oonewarray':    [om.OONewArray],
+    'oosend':        [am.CallMethod],
 }
 
 unary_ops = {

File pypy/translator/avm1/test/browsertest.py

 from BaseHTTPServer import HTTPServer as BaseHTTPServer, BaseHTTPRequestHandler
 from cgi import parse_qs
 
+import time
 import webbrowser
 
 class HTTPServer(BaseHTTPServer):
         return True
     elif string == "false":
         return False
-    elif all(c in "0123456789-" for c in string):
+    elif string == "undefined" or string == "null":
+        return None
+    elif all(c in "123456789-" for c in string):
         return int(string)
+    elif "," in string:
+        return [parse_result(s) for s in string.split(",")]
     return string
 
 class TestCase(object):
         self.serve_data(mime, data)
         
     def do_POST(self):
-        print self.path
         if self.path == "/test.result":
             form = parse_qs(self.rfile.read(int(self.headers['content-length'])))
-            self.server.testcase.result = parse_result(form['result'][0])
+            self.server.testcase.result = form['result'][0]
 
     def serve_data(self, content_type, data):
         self.send_response(200)
 
     def get_result(self):
         testcase = self.httpd.testcase
+        start_time = time.time()
         while testcase.result is None:
+            if time.time() - start_time > 10:
+                assert False
             self.httpd.handle_request()
         return testcase.result
 
     driver.start_server(config.http_port, testcase)
     webbrowser.open('http://localhost:%d/test.html' % config.http_port)
     
-    return driver.get_result()
+    return parse_result(driver.get_result())

File pypy/translator/avm1/test/mylib.py

+from pypy.translator.cli.carbonpython import export
+
+@export(int, int)
+def sum(a, b):
+    return a+b

File pypy/translator/avm1/test/runtest2.py

+
+import py, re, subprocess
+from pypy.translator.translator import TranslationContext
+from pypy.translator.avm.test.browsertest import browsertest
+# from pypy.translator.backendopt.all import backend_optimizations
+# from pypy.translator.js.js import JS
+# from pypy.translator.js.test.browsertest import jstest
+# from pypy.translator.js import conftest
+#from pypy.translator.js.log import log
+from pypy.conftest import option
+from pypy.rpython.test.tool import BaseRtypingTest, OORtypeMixin
+# from pypy.rlib.nonconst import NonConstant
+# from pypy.rpython.ootypesystem import ootype
+
+from pypy.rpython.llinterp import LLException
+
+log = log.runtest
+
+port = 8080
+
+class AVMException(LLException):
+    pass
+
+#def _CLI_is_on_path():
+#    if py.path.local.sysfind('js') is None:  #we recommend Spidermonkey
+#        return False
+#    return True
+
+class compile_function(object):
+    def __init__(self, function, annotations, stackless=False, view=False, html=None, is_interactive=False, root = None, run_browser = True, policy = None):
+
+        self.html = html
+        self.is_interactive = is_interactive
+        t = TranslationContext()
+        
+        if policy is None:
+            from pypy.annotation.policy import AnnotatorPolicy
+            policy = AnnotatorPolicy()
+            policy.allow_someobjects = False
+
+        ann = t.buildannotator(policy=policy)
+        ann.build_types(function, annotations)
+        if view or option.view:
+            t.view()
+        t.buildrtyper(type_system="ootype").specialize()
+
+        if view or option.view:
+            t.view()
+        #self.js = JS(t, [function, callback_function], stackless)
+        self.js = JS(t, function, stackless)
+        self.js.write_source()
+        if root is None and use_tg:
+            from pypy.translator.js.demo.jsdemo.controllers import Root
+            self.root = Root
+        else:
+            self.root = root
+        self.run_browser = run_browser
+        self.function_calls = []
+    
+    def source(self):
+        return self.js.tmpfile.open().read()
+
+    def _conv(self, v):
+        if isinstance(v, str):
+            return repr(v)
+        return str(v).lower()
+
+    def __call__(self, *kwds):
+        return self.call(None, kwds)
+    
+    def call(self, entry_function, kwds):
+        args = ', '.join([self._conv(kw) for kw in kwds]) #lowerstr for (py)False->(js)false, etc.
+
+        if entry_function is None:
+            entry_function = self.js.translator.graphs[0].name
+        else:
+            entry_function = self.js.translator.annotator.bookkeeper.getdesc(entry_function).cached_graph(None)
+        function_call = "%s(%s)" % (entry_function, args)
+        self.function_calls.append(function_call)
+        #if self.js.stackless:
+        #    function_call = "slp_entry_point('%s')" % function_call
+
+        if use_browsertest:
+            if not use_tg:
+                log("Used html: %r" % self.html)
+                output = browsertest(self.js.filename, function_call)
+            else:
+                global port
+                from pypy.translator.js.test.tgtest import run_tgtest
+                out = run_tgtest(self, tg_root = self.root, port=port, run_browser=self.run_browser).results
+                assert out[1] == 'undefined' or out[1] == ""
+                output = out[0]
+                port += 1
+            return self.reinterpret(output)
+        else:
+#            cmd = 'echo "load(\'%s\'); print(%s)" | js 2>&1' % (self.js.filename, function_call)
+#            log(cmd)
+#            output = os.popen(cmd).read().strip()
+            js = subprocess.Popen(["js"], 
+                                  stdin=subprocess.PIPE,
+                                  stdout=subprocess.PIPE,
+                                  stderr=subprocess.PIPE)
+            input = "load(%r);\n" % self.js.filename.strpath
+            for call in self.function_calls[:-1]:
+                input += "%s;\n" % call
+            input += "print(\"'\" + %s + \"'\");\n" % self.function_calls[-1]
+            js.stdin.write(input)
+            stdout, stderr = js.communicate()
+            output = (stderr + stdout).strip()
+        for s in output.split('\n'):
+            log(s)
+
+        m = re.match("'(.*)'", output, re.DOTALL)
+        if not m:
+            log("Error: %s" % output)
+            raise JSException(output)
+        return self.reinterpret(m.group(1))
+
+    def reinterpret(cls, s):
+        #while s.startswith(" "):
+        #    s = s[1:] # :-) quite inneficient, but who cares
+        if s == 'false':
+            res = False
+        elif s == 'true':
+            res = True
+        elif s == 'undefined':
+            res = None
+        elif s == 'inf':
+            res = 1e300 * 1e300
+        elif s == 'NaN':
+            res = (1e300 * 1e300) / (1e300 * 1e300)
+        elif s.startswith('[') or s.startswith('('):
+            l = s[1:-1].split(',')
+            res = [cls.reinterpret(i) for i in l]
+        else:
+            try:
+                res = float(s)
+                if float(int(res)) == res:
+                    return int(res)
+            except ValueError:
+                res = str(s)
+        return res
+    reinterpret = classmethod(reinterpret)
+
+class JsTest(BaseRtypingTest, OORtypeMixin):
+    def _compile(self, _fn, args, policy=None):
+        argnames = _fn.func_code.co_varnames[:_fn.func_code.co_argcount]
+        func_name = _fn.func_name
+        if func_name == '<lambda>':
+            func_name = 'func'
+        source = py.code.Source("""
+        def %s():
+            from pypy.rlib.nonconst import NonConstant
+            res = _fn(%s)
+            if isinstance(res, type(None)):
+                return None
+            else:
+                return str(res)"""
+        % (func_name, ",".join(["%s=NonConstant(%r)" % (name, i) for
+                                   name, i in zip(argnames, args)])))
+        exec source.compile() in locals()
+        return compile_function(locals()[func_name], [], policy=policy)
+
+    def string_to_ll(self, s):
+        return s
+    
+    def interpret(self, fn, args, policy=None):
+        f = self._compile(fn, args, policy)
+        res = f(*args)
+        return res
+
+    def interpret_raises(self, exception, fn, args):
+        #import exceptions # needed by eval
+        #try:
+        #import pdb; pdb.set_trace()
+        try:
+            res = self.interpret(fn, args)
+        except JSException, e:
+            s = e.args[0]
+            assert s.startswith('uncaught exception:')
+            assert re.search(exception.__name__, s)
+        else:
+            raise AssertionError("Did not raise, returned %s" % res)
+        #except ExceptionWrapper, ex:
+        #    assert issubclass(eval(ex.class_name), exception)
+        #else:
+        #    assert False, 'function did raise no exception at all'
+
+    def ll_to_string(self, s):
+        return str(s)
+
+    def ll_to_list(self, l):
+        return l
+
+    def ll_unpack_tuple(self, t, length):
+        assert len(t) == length
+        return tuple(t)
+
+    def class_name(self, value):
+        return value[:-8].split('.')[-1]
+
+    def is_of_instance_type(self, val):
+        m = re.match("^<.* object>$", val)
+        return bool(m)
+
+    def read_attr(self, obj, name):
+        py.test.skip('read_attr not supported on genjs tests')
+
+def check_source_contains(compiled_function, pattern):
+    import re
+    
+    source = compiled_function.js.tmpfile.open().read()
+    return re.search(pattern, source)

File pypy/translator/avm1/test/simpletest.py

+
+from pypy.translator.avm.swf import SwfData
+from pypy.translator.avm.tags import SetBackgroundColor, DefineShape, End
+from pypy.translator.avm.records import ShapeWithStyle, LineStyle, StraightEdgeRecord, StyleChangeRecord
+
+linestyle = LineStyle(3, 0x000000)
+
+shape = ShapeWithStyle()
+shape.add_line_style(linestyle)
+shape.add_shape_record(StyleChangeRecord(20, 20, linestyle))
+shape.add_shape_record(StraightEdgeRecord(100, 100))
+
+swf = SwfData(400, 300)
+swf.add_tag(SetBackgroundColor(0x333333))
+swf.add_tag(DefineShape(shape))
+swf.add_tag(End())
+print swf.serialize()

File pypy/translator/avm1/test/test_backendopt.py

+import py
+from pypy.translator.cli.test.runtest import compile_function
+from pypy.translator.oosupport.test_template.backendopt import BaseTestOptimizedSwitch
+
+class TestOptimizedSwitch(BaseTestOptimizedSwitch):
+    def getcompiled(self, fn, annotation):
+        return compile_function(fn, annotation, backendopt=True)

File pypy/translator/avm1/test/test_bool.py

+import py
+from pypy.translator.cli.test.runtest import CliTest
+from pypy.rpython.test.test_rbool import BaseTestRbool
+
+class TestCliBool(CliTest, BaseTestRbool):
+    pass
+

File pypy/translator/avm1/test/test_builtin.py

+import platform
+import py
+from pypy.translator.cli.test.runtest import CliTest
+from pypy.translator.oosupport.test_template.builtin import BaseTestBuiltin, BaseTestTime
+
+
+def skip_os(self):
+    py.test.skip("CLI doesn't support the os module, yet")
+
+def skip_win():
+    if platform.system() == 'Windows':
+        py.test.skip("Doesn't work on Windows, yet")
+
+class TestCliBuiltin(CliTest, BaseTestBuiltin):
+    test_os_path_exists = skip_os
+    test_os_isdir = skip_os
+    test_os_dup_oo = skip_os
+    test_os_access = skip_os
+        
+    def test_builtin_math_frexp(self):
+        self._skip_powerpc("Mono math floating point problem")
+        BaseTestBuiltin.test_builtin_math_frexp(self)
+
+    def test_debug_llinterpcall(self):
+        py.test.skip("so far, debug_llinterpcall is only used on lltypesystem")
+
+
+class TestCliTime(CliTest, BaseTestTime):
+    pass

File pypy/translator/avm1/test/test_carbonpython.py

+import py
+py.test.skip("it passes usually, but fails on buildbot, no clue why")
+
+import os
+import os.path
+from pypy.tool import udir
+from pypy.translator.cli.rte import Target
+from pypy.translator.cli.carbonpython import DllDef, export, collect_entrypoints,\
+     collect_class_entrypoints, compile_dll
+from pypy.translator.cli.test.runtest import CliFunctionWrapper, CliTest
+
+TEMPLATE = """
+using System;
+using System.Collections;
+class CarbonPytonTest {
+    public static void Main() {
+        %s
+    }
+}
+"""
+
+class TestCarbonPython(CliTest):
+    
+    def _csharp(self, source, references=[], netmodules=[]):
+        tmpfile = udir.udir.join('tmp.cs')
+        tmpfile.write(TEMPLATE % source)
+        flags = ['/r:%s' % ref for ref in references]
+        flags += ['/addmodule:%s' % mod for mod in netmodules]
+        
+        class MyTarget(Target):
+            SOURCES = [str(tmpfile)]
+            FLAGS = flags
+            OUTPUT = 'tmp.exe'
+            SRC_DIR = str(udir.udir)
+
+        func = CliFunctionWrapper(MyTarget.get())
+        return func()
+
+    def test_compilation(self):
+        res = self._csharp('Console.WriteLine(42);')
+        assert res == 42
+
+    def test_func_namespace(self):
+        def foo(x):
+            return x+1
+        def bar(x):
+            return foo(x)
+        foo._namespace_ = 'MyNamespace.MyClass'
+        bar._namespace_ = 'MyClass'
+        res = self.interpret(bar, [41], backendopt=False)
+        assert res == 42
+
+    def test_simple_functions(self):
+        def foo(x):
+            return x+1
+        def bar(x):
+            return x*2
+        dll = DllDef('test', 'Test', [(foo, [int]),
+                                      (bar, [int])])
+        dll.compile()
+        res = self._csharp('Console.WriteLine("{0}, {1}", Test.foo(42), Test.bar(42));', ['test'])
+        assert res == (43, 84)
+
+    def test_export(self):
+        @export(int, float)
+        def foo(x, y):
+            pass
+        @export(int, float, namespace='test')
+        def bar(x, y):
+            pass
+        @export
+        def baz():
+            pass
+
+        assert foo._inputtypes_ == (int, float)
+        assert not hasattr(foo, '_namespace_')
+        assert bar._inputtypes_ == (int, float)
+        assert bar._namespace_ == 'test'
+        assert baz._inputtypes_ == ()
+
+    def test_collect_entrypoints(self):
+        @export(int, float)
+        def foo(x, y):
+            pass
+        def bar(x, y):
+            pass
+        mydict = dict(foo=foo, bar=bar, x=42)
+        entrypoints = collect_entrypoints(mydict)
+        assert entrypoints == [(foo, (int, float))]
+
+    def test_collect_class_entrypoints(self):
+        class NotExported:
+            def __init__(self):
+                pass
+            
+        class MyClass:
+            @export
+            def __init__(self):
+                pass
+            @export(int)
+            def foo(self, x):
+                return x
+
+        assert collect_class_entrypoints(NotExported) == []
+        entrypoints = collect_class_entrypoints(MyClass)
+        assert len(entrypoints) == 2
+        assert entrypoints[0][1] == () # __init__ inputtypes
+        assert entrypoints[1][1] == (MyClass, int) # foo inputtypes
+        
+    def test_compile_class(self):
+        py.test.skip('This test fails every other day. No clue why :-(')
+        class MyClass:
+            @export(int)
+            def __init__(self, x):
+                self.x = x
+            @export(int, int)
+            def add(self, y, z):
+                return self.x + y + z
+        MyClass.__module__ = 'Test' # put the class in the Test namespace
+
+        entrypoints = collect_entrypoints({'MyClass': MyClass})
+        dll = DllDef('test', 'Test', entrypoints)
+        dll.compile()
+        res = self._csharp("""
+            Test.MyClass obj = new Test.MyClass();
+            obj.__init__(39);
+            Console.WriteLine(obj.add(1, 2));
+        """, ['test'])
+        assert res == 42
+
+    def test_export_cliclass(self):
+        py.test.skip('it fails every other day on builbot, no clue why')
+        from pypy.translator.cli.dotnet import CLR
+        
+        @export(CLR.System.Collections.ArrayList, int)
+        def getitem(obj, i):
+            return obj.get_Item(i)
+
+        entrypoints = collect_entrypoints({'getitem': getitem})
+        dll = DllDef('test', 'Test', entrypoints)
+        dll.compile()
+        res = self._csharp("""
+            ArrayList obj = new ArrayList();
+            obj.Add(42);
+            Console.WriteLine(Test.getitem(obj, 0));
+        """, ['test'])
+        assert res == 42
+
+    def test_compile_dll(self):
+        py.test.skip('This test fails every other day. No clue why :-(')
+        cwd, _ = os.path.split(__file__)
+        mylib_py = os.path.join(cwd, 'mylib.py')
+        compile_dll(mylib_py, copy_dll=False)
+        res = self._csharp("""
+            Console.WriteLine(mylib.sum(20, 22));
+        """, ['mylib'])
+        assert res == 42
+
+    def test_compile_dll_alternative_name(self):
+        cwd, _ = os.path.split(__file__)
+        mylib_py = os.path.join(cwd, 'mylib.py')
+        compile_dll(mylib_py, 'mylibxxx.dll', copy_dll=False)
+        res = self._csharp("""
+            Console.WriteLine(mylibxxx.sum(20, 22));
+        """, ['mylibxxx'])
+        assert res == 42
+
+    def test_compile_netmodule(self):
+        def foo(x):
+            return x+1
+        dll = DllDef('mymodule', 'Test', [(foo, [int])], isnetmodule=True)
+        dll.compile()
+        res = self._csharp('Console.WriteLine("{0}", Test.foo(41));',
+                           netmodules = ['mymodule'])
+        

File pypy/translator/avm1/test/test_cast.py

+from pypy.translator.cli.test.runtest import CliTest
+from pypy.translator.oosupport.test_template.cast import BaseTestCast
+
+class TestCast(BaseTestCast, CliTest):
+    pass

File pypy/translator/avm1/test/test_class.py

+import py
+from pypy.translator.cli.test.runtest import CliTest
+from pypy.translator.oosupport.test_template.class_ import BaseTestClass, BaseTestSpecialcase
+
+# ====> ../../oosupport/test_template/class_.py
+
+class TestCliClass(CliTest, BaseTestClass):    
+    pass
+
+class TestCliSpecialCase(CliTest, BaseTestSpecialcase):
+    pass

File pypy/translator/avm1/test/test_constant.py

+from pypy.translator.oosupport.test_template.constant import BaseTestConstant
+from pypy.translator.cli.test.runtest import CliTest
+
+class TestConstant(BaseTestConstant, CliTest):
+    pass

File pypy/translator/avm1/test/test_cts.py

+from pypy.translator.cli import cts
+
+def test_primitive():
+    void = cts.CliPrimitiveType('void')
+    assert str(void) == void.typename() == 'void'
+    assert void == cts.CliPrimitiveType('void')
+
+def test_class():
+    Math = cts.CliClassType('mscorlib', 'System.Math')
+    assert str(Math) == Math.typename() == 'class [mscorlib]System.Math'
+    assert Math.classname() == '[mscorlib]System.Math'
+    assert Math == cts.CliClassType('mscorlib', 'System.Math')
+
+def test_generic():
+    Dict = cts.CliGenericType('mscorlib', 'System.Dict', 2)
+    assert str(Dict) == Dict.typename() == 'class [mscorlib]System.Dict`2<!0, !1>'
+    
+    int32 = cts.CliPrimitiveType('int32')
+    Math = cts.CliClassType('mscorlib', 'System.Math')
+    MyDict = Dict.specialize(int32, Math)
+    assert isinstance(MyDict, cts.CliSpecializedType)
+    classname = '[mscorlib]System.Dict`2<int32, class [mscorlib]System.Math>'
+    assert str(MyDict) == MyDict.typename() == 'class ' + classname
+    assert MyDict.classname() == classname

File pypy/translator/avm1/test/test_dict.py

+import py
+from pypy.translator.cli.test.runtest import CliTest
+import pypy.translator.oosupport.test_template.dict as oodict
+
+class TestCliDict(CliTest, oodict.BaseTestDict):
+    def test_dict_of_dict(self):
+        py.test.skip("CLI doesn't support recursive dicts")
+
+    def test_recursive(self):
+        py.test.skip("CLI doesn't support recursive dicts")
+
+    def test_dict_of_void_special_case(self):
+        def fn(n):
+            d = {}
+            for i in xrange(n):
+                d[i] = None
+            return d[0]
+        assert self.interpret(fn, [2]) is None
+
+class TestCliEmptyDict(CliTest, oodict.BaseTestEmptyDict):
+    pass
+
+class TestCliConstantDict(CliTest, oodict.BaseTestConstantDict):
+    pass

File pypy/translator/avm1/test/test_dotnet.py

+import py
+from pypy.annotation.annrpython import RPythonAnnotator
+from pypy.annotation import model as annmodel
+from pypy.rpython.ootypesystem import ootype
+from pypy.rpython.ootypesystem.ootype import meth, Meth, Char, Signed, Float, String,\
+     ROOT, overload, Instance, new
+from pypy.translator.cli.test.runtest import CliTest
+from pypy.translator.cli.dotnet import SomeCliClass, SomeCliStaticMethod,\
+     NativeInstance, CLR, box, unbox, OverloadingResolver, NativeException,\
+     native_exc, new_array, init_array, typeof, eventhandler, clidowncast,\
+     fieldinfo_for_const, classof, cast_record_to_object, cast_object_to_record
+
+System = CLR.System
+ArrayList = CLR.System.Collections.ArrayList
+OpCodes = System.Reflection.Emit.OpCodes
+DynamicMethod = System.Reflection.Emit.DynamicMethod
+Utils = CLR.pypy.runtime.Utils
+FUNCTYPE = ootype.StaticMethod([ootype.Signed, ootype.Signed], ootype.Signed)
+
+class TestDotnetAnnotation(object):
+
+    def test_overloaded_meth_string(self):
+        C = Instance("test", ROOT, {},
+                     {'foo': overload(meth(Meth([Char], Signed)),
+                                      meth(Meth([String], Float)),
+                                      resolver=OverloadingResolver),
+                      'bar': overload(meth(Meth([Signed], Char)),
+                                      meth(Meth([Float], String)),
+                                      resolver=OverloadingResolver)})
+        def fn1():
+            return new(C).foo('a')
+        def fn2():
+            return new(C).foo('aa')
+        def fn3(x):
+            return new(C).bar(x)
+        a = RPythonAnnotator()
+        assert isinstance(a.build_types(fn1, []), annmodel.SomeInteger)
+        assert isinstance(a.build_types(fn2, []), annmodel.SomeFloat)
+        assert isinstance(a.build_types(fn3, [int]), annmodel.SomeChar)
+        assert isinstance(a.build_types(fn3, [float]), annmodel.SomeString)
+
+    def test_class(self):
+        def fn():
+            return System.Math
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, SomeCliClass)
+        assert s.const is System.Math
+
+    def test_fullname(self):
+        def fn():
+            return CLR.System.Math
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, SomeCliClass)
+        assert s.const is System.Math
+
+    def test_staticmeth(self):
+        def fn():
+            return System.Math.Abs
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, SomeCliStaticMethod)
+        assert s.cli_class is System.Math
+        assert s.meth_name == 'Abs'
+
+    def test_staticmeth_call(self):
+        def fn1():
+            return System.Math.Abs(42)
+        def fn2():
+            return System.Math.Abs(42.5)
+        a = RPythonAnnotator()
+        assert type(a.build_types(fn1, [])) is annmodel.SomeInteger
+        assert type(a.build_types(fn2, [])) is annmodel.SomeFloat
+
+    def test_new_instance(self):
+        def fn():
+            return ArrayList()
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert isinstance(s.ootype, NativeInstance)
+        assert s.ootype._name == '[mscorlib]System.Collections.ArrayList'
+
+    def test_box(self):
+        def fn():
+            return box(42)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.ootype._name == '[mscorlib]System.Object'
+        assert not s.can_be_None
+
+    def test_box_can_be_None(self):
+        def fn(flag):
+            if flag:
+                return box(42)
+            else:
+                return box(None)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [bool])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.ootype._name == '[mscorlib]System.Object'
+        assert s.can_be_None
+
+    def test_unbox(self):
+        def fn():
+            x = box(42)
+            return unbox(x, ootype.Signed)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeInteger)
+
+    def test_unbox_can_be_None(self):
+        class Foo:
+            pass
+        def fn():
+            x = box(42)
+            return unbox(x, Foo)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeInstance)
+        assert s.can_be_None
+
+    def test_array(self):
+        def fn():
+            x = ArrayList()
+            return x.ToArray()
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.ootype._isArray
+        assert s.ootype._ELEMENT._name == '[mscorlib]System.Object'
+
+    def test_array_getitem(self):
+        def fn():
+            x = ArrayList().ToArray()
+            return x[0]
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.ootype._name == '[mscorlib]System.Object'
+
+    def test_mix_None_and_instance(self):
+        def fn(x):
+            if x:
+                return None
+            else:
+                return box(42)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [bool])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.can_be_None == True
+
+    def test_box_instance(self):
+        class Foo:
+            pass
+        def fn():
+            return box(Foo())
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeOOInstance)
+        assert s.ootype._name == '[mscorlib]System.Object'
+
+    def test_unbox_instance(self):
+        class Foo:
+            pass
+        def fn():
+            boxed = box(Foo())
+            return unbox(boxed, Foo)
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeInstance)
+        assert s.classdef.name.endswith('Foo')
+
+    def test_can_be_None(self):
+        def fn():
+            ttype = System.Type.GetType('foo')
+            return ttype.get_Namespace()
+        a = RPythonAnnotator()
+        s = a.build_types(fn, [])
+        assert isinstance(s, annmodel.SomeString)
+        assert s.can_be_None
+
+
+class TestDotnetRtyping(CliTest):
+    def _skip_pythonnet(self, msg):
+        pass
+
+    def test_staticmeth_call(self):
+        def fn(x):
+            return System.Math.Abs(x)
+        assert self.interpret(fn, [-42]) == 42
+
+    def test_staticmeth_overload(self):
+        self._skip_pythonnet('Pythonnet bug!')
+        def fn(x, y):
+            return System.Math.Abs(x), System.Math.Abs(y)
+        res = self.interpret(fn, [-42, -42.5])
+        item0, item1 = self.ll_to_tuple(res)
+        assert item0 == 42
+        assert item1 == 42.5
+
+    def test_tostring(self):
+        StringBuilder = CLR.System.Text.StringBuilder
+        def fn():
+            x = StringBuilder()
+            x.Append(box("foo")).Append(box("bar"))
+            return x.ToString()
+        res = self.ll_to_string(self.interpret(fn, []))
+        assert res == 'foobar'
+    
+    def test_box(self):
+        def fn():
+            x = ArrayList()
+            x.Add(box(42))
+            x.Add(box('Foo'))
+            return x.get_Count()
+        assert self.interpret(fn, []) == 2
+
+    def test_whitout_box(self):
+        def fn():
+            x = ArrayList()
+            x.Add(42) # note we have forgot box()
+        py.test.raises(TypeError, self.interpret, fn, [])
+
+    def test_unbox(self):
+        def fn():
+            x = ArrayList()
+            x.Add(box(42))
+            return unbox(x.get_Item(0), ootype.Signed)
+        assert self.interpret(fn, []) == 42
+
+    def test_unbox_string(self):
+        def fn():
+            x = ArrayList()
+            x.Add(box('foo'))
+            return unbox(x.get_Item(0), ootype.String)
+        assert self.interpret(fn, []) == 'foo'
+
+    def test_box_method(self):
+        def fn():
+            x = box(42)
+            t = x.GetType()
+            return t.get_Name()
+        res = self.interpret(fn, [])
+        assert res == 'Int32'
+
+    def test_box_object(self):
+        def fn():
+            return box(System.Object()).ToString()
+        res = self.interpret(fn, [])
+        assert res == 'System.Object'
+
+    def test_array(self):
+        def fn():
+            x = ArrayList()
+            x.Add(box(42))
+            array = x.ToArray()
+            return unbox(array[0], ootype.Signed)
+        assert self.interpret(fn, []) == 42
+
+    def test_new_array(self):
+        def fn():
+            x = new_array(System.Object, 2)
+            x[0] = box(42)
+            x[1] = box(43)
+            return unbox(x[0], ootype.Signed) + unbox(x[1], ootype.Signed)
+        assert self.interpret(fn, []) == 42+43
+
+    def test_init_array(self):
+        def fn():
+            x = init_array(System.Object, box(42), box(43))
+            return unbox(x[0], ootype.Signed) + unbox(x[1], ootype.Signed)
+        assert self.interpret(fn, []) == 42+43
+
+    def test_array_setitem_None(self):
+        py.test.skip('Mono bug :-(')
+        def fn():
+            x = init_array(System.Object, box(42), box(43))
+            x[0] = None
+            return x[0]
+        assert self.interpret(fn, []) is None
+
+    def test_array_length(self):
+        def fn():
+            x = init_array(System.Object, box(42), box(43))
+            return len(x)
+        assert self.interpret(fn, []) == 2
+
+    def test_null(self):
+        def fn():
+            return System.Object.Equals(None, None)
+        assert self.interpret(fn, []) == True
+
+    def test_null_bound_method(self):
+        def fn():
+            x = ArrayList()
+            x.Add(None)
+            return x.get_Item(0)
+        assert self.interpret(fn, []) is None
+
+    def test_native_exception_precise(self):
+        ArgumentOutOfRangeException = NativeException(CLR.System.ArgumentOutOfRangeException)
+        def fn():
+            x = ArrayList()
+            try:
+                x.get_Item(0)
+                return False
+            except ArgumentOutOfRangeException:
+                return True
+        assert self.interpret(fn, []) == True
+
+    def test_native_exception_superclass(self):
+        SystemException = NativeException(CLR.System.Exception)
+        def fn():
+            x = ArrayList()
+            try:
+                x.get_Item(0)
+                return False
+            except SystemException:
+                return True
+        assert self.interpret(fn, []) == True
+
+    def test_native_exception_object(self):
+        SystemException = NativeException(CLR.System.Exception)
+        def fn():
+            x = ArrayList()
+            try:
+                x.get_Item(0)
+                return "Impossible!"
+            except SystemException, e:
+                ex = native_exc(e)
+                return ex.get_Message()
+        res = self.ll_to_string(self.interpret(fn, []))
+        assert res.startswith("Index is less than 0")
+
+    def test_native_exception_invoke(self):
+        TargetInvocationException = NativeException(CLR.System.Reflection.TargetInvocationException)
+        def fn():
+            x = ArrayList()
+            t = x.GetType()
+            meth = t.GetMethod('get_Item')
+            args = init_array(System.Object, box(0))
+            try:
+                meth.Invoke(x, args)
+                return "Impossible!"
+            except TargetInvocationException, e:
+                inner = native_exc(e).get_InnerException()
+                message = str(inner.get_Message())
+                return message
+        res = self.ll_to_string(self.interpret(fn, []))
+        assert res.startswith("Index is less than 0")
+
+    def test_typeof(self):
+        def fn():
+            x = box(42)
+            return x.GetType() ==  typeof(System.Int32)
+        res = self.interpret(fn, [])
+        assert res is True
+
+    def test_typeof_pypylib(self):
+        DelegateType = CLR.pypy.test.DelegateType_int__int_2
+        def fn():
+            return typeof(DelegateType) is not None
+        res = self.interpret(fn, [])
+        assert res is True
+
+    def test_typeof_functype(self):
+        # this test is overridden in TestPythonnet
+        def fn():
+            t = typeof(FUNCTYPE)
+            return t.get_Name()
+        res = self.interpret(fn, [])
+        assert res.startswith('StaticMethod__')
+
+    def test_clidowncast(self):
+        def fn():
+            a = ArrayList()
+            b = ArrayList()
+            a.Add(b)
+            c = a.get_Item(0) # type of c is Object
+            c = clidowncast(c, ArrayList)
+            c.Add(None)
+            return c.get_Item(0)
+        res = self.interpret(fn, [])
+        assert res is None
+
+    def test_clidowncast_lltype(self):
+        ARRAY_LIST = ArrayList._INSTANCE
+        def fn():
+            a = ArrayList()
+            b = ArrayList()
+            a.Add(b)
+            c = a.get_Item(0) # type of c is Object
+            c = clidowncast(c, ARRAY_LIST)
+            c.Add(None)
+            return c.get_Item(0)
+        res = self.interpret(fn, [])
+        assert res is None
+
+    def test_mix_None_and_instance(self):
+        def g(x):
+            return x
+        def fn(flag):
+            if flag:
+                x = None
+            else:
+                x = box(42)
+            return g(x)
+        res = self.interpret(fn, [1])
+        assert res is None
+
+    def test_box_unbox_instance(self):
+        class Foo:
+            pass
+        def fn():
+            obj = Foo()
+            b_obj = box(obj)
+            obj2 = unbox(b_obj, Foo)
+            return obj is obj2
+        res = self.interpret(fn, [])
+        assert res is True
+
+    def test_unbox_instance_fail(self):
+        class Foo:
+            pass
+        def fn():
+            b_obj = box(42)
+            return unbox(b_obj, Foo)
+        res = self.interpret(fn, [])
+        assert res is None
+
+    def test_box_unbox_ooinstance(self):
+        A = ootype.Instance('A', ootype.ROOT, {'xx': ootype.Signed})
+        def fn(flag):
+            a = ootype.new(A)
+            a.xx = 42
+            b_obj = box(a)
+            a2 = unbox(b_obj, A)
+            return a2.xx
+        res = self.interpret(fn, [True])
+        assert res == 42
+
+    def test_box_unbox_ooinstance_fail(self):
+        A = ootype.Instance('A', ootype.ROOT, {'xx': ootype.Signed})
+        def fn(flag):
+            b_obj = System.Object()
+            a2 = unbox(b_obj, A)
+            return a2
+        res = self.interpret(fn, [True])
+        assert res is None
+
+    def test_box_unbox_oorecord(self):
+        A = ootype.Record({'xx': ootype.Signed})
+        def fn(flag):
+            a = ootype.new(A)
+            a.xx = 42
+            b_obj = box(a)
+            a2 = unbox(b_obj, A)
+            return a2.xx
+        res = self.interpret(fn, [True])
+        assert res == 42
+
+    def test_instance_wrapping(self):
+        class Foo:
+            pass
+        def fn():
+            obj = Foo()
+            x = ArrayList()
+            x.Add(box(obj))
+            obj2 = unbox(x.get_Item(0), Foo)
+            return obj is obj2
+        res = self.interpret(fn, [])
+        assert res is True
+
+    def test_compare_string_None(self):
+        from pypy.rlib.nonconst import NonConstant
+        def null():
+            if NonConstant(True):
+                return None
+            else:
+                return ""
+        
+        def fn():
+            ttype = System.Type.GetType('Consts, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
+            namespace = ttype.get_Namespace()
+            if namespace is not None:
+                return False
+            else:
+                return True
+        res = self.interpret(fn, [], backendopt=False)
+        assert res is True
+
+    def test_delegate(self):
+        class Foo:
+            def __init__(self):
+                self.x = 0
+            def m(self, sender, args):
+                self.x = 42
+
+        def fn(flag):
+            f = Foo()
+            if flag:
+                f.m(None, None)
+            delegate = eventhandler(f.m)
+            delegate.Invoke(None, None)
+            return f.x
+        res = self.interpret(fn, [False])
+        assert res == 42
+
+    def test_static_fields(self):
+        DummyClass = CLR.pypy.test.DummyClass
+        def fn():
+            obj = System.Object()
+            DummyClass.myfield = obj
+            return DummyClass.myfield is obj
+        res = self.interpret(fn, [])
+        assert res
+
+    def test_pypylib(self):
+        def fn():
+            return CLR.pypy.runtime.Utils.OOString(42, -1)
+        res = self.interpret(fn, [])
+        assert self.ll_to_string(res) == '42'
+
+    def test_call_delegate(self):
+        def build_fn():
+            tInt = typeof(System.Int32)
+            args = init_array(System.Type, tInt, tInt)
+            meth = Utils.CreateDynamicMethod("add", tInt, args)
+            il = meth.GetILGenerator()
+            il.Emit(OpCodes.Ldarg_0)
+            il.Emit(OpCodes.Ldarg_1)
+            il.Emit(OpCodes.Add)
+            il.Emit(OpCodes.Ret)
+            myfunc = meth.CreateDelegate(typeof(FUNCTYPE))
+            return myfunc
+
+        def fn(x, y):
+            myfunc = unbox(build_fn(), FUNCTYPE)
+            a = myfunc(x, y)
+            mytuple = (x, y)
+            b = myfunc(*mytuple)
+            return a+b
+        res = self.interpret(fn, [10, 11])
+        assert res == 42
+
+    def test_bound_delegate(self):
+        def build_fn():
+            tObjArray = System.Type.GetType("System.Object[]")
+            tInt = typeof(System.Int32)
+            args = init_array(System.Type, tObjArray, tInt, tInt)
+            meth = Utils.CreateDynamicMethod("add", tInt, args)
+            il = meth.GetILGenerator()
+            il.Emit(OpCodes.Ldarg_1)
+            il.Emit(OpCodes.Ldarg_2)
+            il.Emit(OpCodes.Add)
+            il.Emit(OpCodes.Ret)
+            array = new_array(System.Object, 0)
+            myfunc = meth.CreateDelegate(typeof(FUNCTYPE), array)
+            return myfunc
+
+        def fn():
+            myfunc = unbox(build_fn(), FUNCTYPE)
+            return myfunc(30, 12)
+        res = self.interpret(fn, [])
+        assert res == 42
+
+    def test_valuetype_field(self):
+        class Foo:
+            def __init__(self, x):
+                self.x = x
+
+        def fn():
+            f = Foo(OpCodes.Add)
+            return f
+        self.interpret(fn, [])
+
+    def test_fieldinfo_for_const(self):
+        A = ootype.Instance('A', ootype.ROOT, {'xx': ootype.Signed})
+        const = ootype.new(A)
+        const.xx = 42
+        def fn():
+            fieldinfo = fieldinfo_for_const(const)
+            obj = fieldinfo.GetValue(None)
+            # get the 'xx' field by using reflection
+            t = obj.GetType()
+            x_info = t.GetField('xx')
+            x_value = x_info.GetValue(obj)
+            return unbox(x_value, ootype.Signed)
+        res = self.interpret(fn, [])
+        assert res == 42
+
+    def test_fieldinfo_for_const_pbc(self):
+        A = ootype.Instance('A', ootype.ROOT, {'xx': ootype.Signed})
+        const = ootype.new(A)
+        fieldinfo = fieldinfo_for_const(const)
+        def fn():
+            const.xx = 42
+            obj = fieldinfo.GetValue(None)
+            # get the 'xx' field by using reflection
+            t = obj.GetType()
+            x_info = t.GetField('xx')
+            x_value = x_info.GetValue(obj)
+            return unbox(x_value, ootype.Signed)
+        res = self.interpret(fn, [])
+        assert res == 42
+
+    def test_classof(self):
+        int32_class = classof(System.Int32)
+        def fn():
+            int32_obj = box(int32_class)
+            int32_type = clidowncast(int32_obj, System.Type)
+            return int32_type.get_Name()
+        assert self.interpret(fn, []) == 'Int32'
+
+    def test_classof_compare(self):
+        int32_a = classof(System.Int32)
+        int32_b = classof(System.Int32)
+        def fn():
+            return int32_a is int32_b
+        assert self.interpret(fn, [])
+
+    def test_classof_functype(self):
+        # this test is overridden in TestPythonnet
+        c = classof(FUNCTYPE)
+        def fn():
+            obj = box(c)
+            t = clidowncast(obj, System.Type)
+            return t.get_Name()
+        res = self.interpret(fn, [])
+        assert res.startswith('StaticMethod__')
+
+    def test_mix_classof(self):
+        a = classof(System.Int32)
+        b = classof(FUNCTYPE)
+        def fn(flag):
+            if flag:
+                x = a
+            else:
+                x = b
+            return clidowncast(box(x), System.Type).get_Name()
+        res = self.interpret(fn, [True])
+        assert res == 'Int32'
+
+    def test_cast_record(self):
+        T = ootype.Record({'x': ootype.Signed})
+        record = ootype.new(T)
+        def fn(flag):
+            if flag:
+                obj = cast_record_to_object(record)
+            else:
+                obj = System.Object()
+            record2 = cast_object_to_record(T, obj)
+            return record is record2
+        res = self.interpret(fn, [True])
+        assert res
+
+    def test_cast_record_pbc(self):