Commits

Maciej Fijalkowski committed 93c02fe

move stuff around

  • Participants
  • Parent commits c2a22f8
  • Branches result-in-resops

Comments (0)

Files changed (6)

File pypy/jit/metainterp/resoperation.py

     # debug
     name = ""
     pc = 0
+    _counter = 0
 
     _hash = 0
     opnum = 0
 
     is_mutable = False
-    _forwarded = None
+    _forwarded = None    
 
     @classmethod
     def getopnum(cls):
         except NotImplementedError:
             return object.__repr__(self)
 
+    def __str__(self):
+        if not hasattr(self, '_str'):
+            if self.type == INT:
+                t = 'i'
+            elif self.type == FLOAT:
+                t = 'f'
+            else:
+                t = 'p'
+            self._str = '%s%d' % (t, AbstractResOp._counter)
+            AbstractResOp._counter += 1
+        return self._str
+
     def repr(self, graytext=False):
         # RPython-friendly version
+        args = self.getarglist()
+        argsrepr = ', '.join([str(a) for a in args])
         resultrepr = self.getresultrepr()
         if resultrepr is not None:
-            sres = '%s = ' % (resultrepr,)
+            sres = '%s = ' % (str(self),)
         else:
             sres = ''
         if self.name:
                 prefix = "\f%s\f" % prefix
         else:
             prefix = ""
-        args = self.getarglist()
         descr = self.getdescr()
         if descr is None or we_are_translated():
-            return '%s%s%s(%s)' % (prefix, sres, self.getopname(),
-                                 ', '.join([str(a) for a in args]))
+            return '%s%s%s(%s)' % (prefix, sres, self.getopname(), argsrepr)
         else:
             return '%s%s%s(%s, descr=%r)' % (prefix, sres, self.getopname(),
-                                             ', '.join([str(a) for a in args]), descr)
+                                             argsrepr, descr)
 
     @classmethod
     def getopname(cls):
 class ResOpInt(object):
     _mixin_ = True
     type = INT
-    
+
     def __init__(self, intval):
         assert isinstance(intval, int)
         self.intval = intval
 class ResOpFloat(object):
     _mixin_ = True
     type = FLOAT
-    
+
     def __init__(self, floatval):
         #assert isinstance(floatval, float)
         # XXX not sure between float or float storage
 class ResOpPointer(object):
     _mixin_ = True
     type = REF
-    
+
     def __init__(self, pval):
         assert lltype.typeOf(pval) == llmemory.GCREF
         self.pval = pval

File pypy/jit/metainterp/test/test_resoperation.py

 def test_repr():
     op = rop.create_resop_0(rop.rop.GUARD_NO_EXCEPTION, None)
     assert repr(op) == 'guard_no_exception()'
-    op = rop.create_resop_2(rop.rop.INT_ADD, 3, FakeBox("a"), FakeBox("b"))
-    assert repr(op) == '3 = int_add(a, b)'
-    # XXX more tests once we decide what we actually want to print
+    c = op._counter
+    i0 = rop.create_resop_0(rop.rop.INPUT_i, 3)
+    op = rop.create_resop_2(rop.rop.INT_ADD, 3, i0, i0)
+    assert repr(op) == 'i%d = int_add(i%d, i%d)' % (c+1, c, c)
+    assert str(op) == 'i%d' % (c + 1,)
 
 class MockOpt(object):
     def __init__(self, replacements):

File pypy/jit/metainterp/typesystem.py

     nullptr = staticmethod(lltype.nullptr)
     cast_instance_to_base_ref = staticmethod(cast_instance_to_base_ptr)
     BASETYPE = llmemory.GCREF
-    BoxRef = resoperation.BoxPtr
     ConstRef = resoperation.ConstPtr
     loops_done_with_this_frame_ref = None # patched by compile.py
     NULLREF = resoperation.ConstPtr.value
     def get_exception_box(self, etype):
         return resoperation.ConstInt(etype)
 
-    def get_exc_value_box(self, evalue):
-        return resoperation.BoxPtr(evalue)
-
     def get_exception_obj(self, evaluebox):
         # only works when translated
         obj = evaluebox.getref(lltype.Ptr(rclass.OBJECT))
     nullptr = staticmethod(ootype.null)
     cast_instance_to_base_ref = staticmethod(cast_instance_to_base_obj)
     BASETYPE = ootype.Object
-    #BoxRef = resoperation.BoxObj
     #ConstRef = resoperation.ConstObj
     loops_done_with_this_frame_ref = None # patched by compile.py
     #$NULLREF = resoperation.ConstObj.value
     def get_exception_box(self, etype):
         return resoperation.ConstObj(etype)
 
-    def get_exc_value_box(self, evalue):
-        return resoperation.BoxObj(evalue)
-
     def get_exception_obj(self, evaluebox):
         # only works when translated
         obj = evaluebox.getref(ootype.ROOT)

File pypy/jit/tool/oparser.py

 
 from pypy.jit.metainterp.resoperation import rop, opclasses, rop_lowercase,\
      ResOpWithDescr, N_aryOp, UnaryOp, PlainResOp, create_resop_dispatch,\
-     ResOpNone
+     ResOpNone, create_resop_0, example_for_opnum
 from pypy.rpython.lltypesystem import lltype, llmemory
 
 class ParseError(Exception):
 
     use_mock_model = False
 
-    def __init__(self, input, cpu, namespace, type_system, boxkinds,
-                 invent_fail_descr=True,
-                 nonstrict=False, results=None, process_guard=None):
+    def __init__(self, input, cpu, namespace, type_system,
+                 invent_fail_descr=True, results=None,
+                 guards_with_failargs=False):
         self.input = input
         self.vars = {}
         self.cpu = cpu
         self._consts = namespace
         self.type_system = type_system
-        self.boxkinds = boxkinds or {}
+        self.guards_with_failargs = guards_with_failargs
         if namespace is not None:
             self._cache = namespace.setdefault('_CACHE_', {})
         else:
             self._cache = {}
         self.invent_fail_descr = invent_fail_descr
-        self.nonstrict = nonstrict
         self.model = get_model(self.use_mock_model)
         self.original_jitcell_token = self.model.JitCellToken()
         self.results = results
-        self.process_guard = process_guard
 
     def get_const(self, name, typ):
         if self._consts is None:
             return self._cache[self.type_system, elem]
         except KeyError:
             pass
-        if elem.startswith('i'):
-            # integer
-            box = self.model.BoxInt()
-            _box_counter_more_than(self.model, elem[1:])
-        elif elem.startswith('f'):
-            box = self.model.BoxFloat()
-            _box_counter_more_than(self.model, elem[1:])
-        elif elem.startswith('p'):
-            # pointer
-            ts = getattr(self.cpu, 'ts', self.model.llhelper)
-            box = ts.BoxRef()
-            _box_counter_more_than(self.model, elem[1:])
+        if elem[0] in 'ifp':
+            if elem[0] == 'p':
+                p = 'r'
+            else:
+                p = elem[0]
+            opnum = getattr(rop, 'INPUT_' + p)
+            box = create_resop_0(opnum, example_for_opnum(opnum))
         else:
-            for prefix, boxclass in self.boxkinds.iteritems():
-                if elem.startswith(prefix):
-                    box = boxclass()
-                    break
-            else:
-                raise ParseError("Unknown variable type: %s" % elem)
+            raise ParseError("Unknown variable type: %s" % elem)
         self._cache[self.type_system, elem] = box
         box._str = elem
         return box
             elif arg.startswith('ConstPtr('):
                 name = arg[len('ConstPtr('):-1]
                 return self.get_const(name, 'ptr')
-            if arg not in self.vars and self.nonstrict:
-                self.newvar(arg)
+            if arg not in self.vars:
+                raise Exception("unexpected var %s" % (arg,))
             return self.vars[arg]
 
     def _example_for(self, opnum):
             i = line.find('[', endnum) + 1
             j = line.find(']', i)
             if i <= 0 or j <= 0:
-                if not self.nonstrict:
+                if self.guards_with_failargs:
                     raise ParseError("missing fail_args for guard operation")
                 fail_args = None
             else:
+                if not self.guards_with_failargs:
+                    raise ParseError("fail_args should be NULL")
                 fail_args = []
                 if i < j:
                     for arg in line[i:j].split(','):
         opres = self.create_op(opnum, result, args, descr)
         self.vars[res] = opres
         if fail_args is not None:
-            opres.set_extra("failargs", fail_args)
-        if self.process_guard and opres.is_guard():
-            self.process_guard(opres, self)
+            explode
         return opres
 
     def parse_op_no_result(self, line):
         opnum, args, descr, fail_args = self.parse_op(line)
         res = self.create_op(opnum, None, args, descr)
         if fail_args is not None:
-            res.set_extra("failargs", fail_args)
-        if self.process_guard and res.is_guard():
-            self.process_guard(res, self)
+            explode
         return res
 
     def parse_next_op(self, line, num):
         line = lines[0]
         base_indent = len(line) - len(line.lstrip(' '))
         line = line.strip()
-        if not line.startswith('[') and self.nonstrict:
-            return base_indent, [], lines
+        if not line.startswith('['):
+            raise ParseError("error parsing %s as inputargs" % (line,))
         lines = lines[1:]
         if line == '[]':
             return base_indent, [], lines
         inpargs = self.parse_header_line(line[1:-1])
         return base_indent, inpargs, lines
 
-def parse(input, cpu=None, namespace=None, type_system='lltype',
-          boxkinds=None, invent_fail_descr=True,
-          no_namespace=False, nonstrict=False, OpParser=OpParser,
-          results=None, process_guard=None):
-    if namespace is None and not no_namespace:
+DEFAULT = object()
+
+def parse(input, cpu=None, namespace=DEFAULT, type_system='lltype',
+          invent_fail_descr=True, OpParser=OpParser,
+          results=None, guards_with_failargs=False):
+    if namespace is DEFAULT:
         namespace = {}
-    return OpParser(input, cpu, namespace, type_system, boxkinds,
-                    invent_fail_descr, nonstrict, results,
-                    process_guard).parse()
+    return OpParser(input, cpu, namespace, type_system,
+                    invent_fail_descr, results, guards_with_failargs).parse()
 
 def pure_parse(*args, **kwds):
     kwds['invent_fail_descr'] = False
     return parse(*args, **kwds)
-
-
-def _box_counter_more_than(model, s):
-    if s.isdigit():
-        model.Box._counter = max(model.Box._counter, int(s)+1)

File pypy/jit/tool/oparser_model.py

 def get_real_model():
     class LoopModel(object):
         from pypy.jit.metainterp.history import TreeLoop, JitCellToken
-        from pypy.jit.metainterp.resoperation import Box, BoxInt, BoxFloat
         from pypy.jit.metainterp.resoperation import ConstInt,\
              ConstPtr, ConstFloat
         from pypy.jit.metainterp.history import BasicFailDescr, TargetToken
         class BasicFailDescr(object):
             I_am_a_descr = True
 
-        class Box(object):
-            _counter = 0
-            type = 'b'
-
-            def __init__(self, value=0):
-                self.value = value
-
-            def __repr__(self):
-                result = str(self)
-                result += '(%s)' % self.value
-                return result
-
-            def __str__(self):
-                if not hasattr(self, '_str'):
-                    self._str = '%s%d' % (self.type, Box._counter)
-                    Box._counter += 1
-                return self._str
-
-            def is_constant(self):
-                return False
-
-        class BoxInt(Box):
-            type = 'i'
-
-        class BoxFloat(Box):
-            type = 'f'
-
-        class BoxRef(Box):
-            type = 'p'
-
         class Const(object):
             def __init__(self, value=None):
                 self.value = value
         class llhelper(object):
             pass
 
-    MockLoopModel.llhelper.BoxRef = MockLoopModel.BoxRef
-
     return MockLoopModel
 
 
     else:
         model = get_real_model()
 
-    #class ExtendedTreeLoop(model.TreeLoop):
-
-        # def getboxes(self):
-        #     def allboxes():
-        #         for box in self.inputargs:
-        #             yield box
-        #         for op in self.operations:
-        #             yield op
-
-        #     boxes = Boxes()
-        #     for box in allboxes():
-        #         if isinstance(box, model.Box):
-        #             name = str(box)
-        #             setattr(boxes, name, box)
-        #     return boxes
-
-    #    def setvalues(self, **kwds):
-    #        boxes = self.getboxes()
-    #        for name, value in kwds.iteritems():
-    #            getattr(boxes, name).value = value
-
     model.ExtendedTreeLoop = model.TreeLoop
     return model

File pypy/jit/tool/test/test_oparser.py

 from pypy.rpython.lltypesystem import lltype, llmemory
 
 from pypy.jit.tool.oparser import parse, OpParser
-from pypy.jit.metainterp.resoperation import rop, BoxInt
+from pypy.jit.metainterp.resoperation import rop
 from pypy.jit.metainterp.history import AbstractDescr, JitCellToken,\
      TargetToken
 
         #assert loop.operations[-1].getdescr()
         # descr is invented by optimizations
 
-    def test_const_ptr_subops(self):
-        x = """
-        [p0]
-        guard_class(p0, ConstClass(vtable)) []
-        """
-        S = lltype.Struct('S')
-        vtable = lltype.nullptr(S)
-        loop = self.parse(x, None, locals())
-        assert len(loop.operations) == 1
-        #assert loop.operations[0].getdescr()
-        # descr is invented by optimizations
-        assert loop.operations[0].get_extra("failargs") == []
-
     def test_descr(self):
         class Xyz(AbstractDescr):
             I_am_a_descr = True # for the mock case
     def test_after_fail(self):
         x = """
         [i0]
-        guard_value(i0, 3) []
+        guard_value(i0, 3)
         i1 = int_add(1, 2)
         """
         loop = self.parse(x, None, {})
         '''
         loop = self.parse(x)
         box = loop.operations[0].getarg(0)
-        # we cannot use isinstance, because in case of mock the class will be
-        # constructed on the fly
-        assert box.__class__.__name__ == 'BoxFloat'
+        assert box.type == 'f'
 
     def test_debug_merge_point(self):
-        x = '''
+        x = """
         []
         debug_merge_point(0, 0, "info")
         debug_merge_point(0, 0, 'info')
         debug_merge_point(1, 1, '<some ('other.')> info')
         debug_merge_point(0, 0, '(stuff) #1')
-        '''
+        """
         loop = self.parse(x)
         assert loop.operations[0].getarg(2)._get_str() == 'info'
         assert loop.operations[0].getarg(1).value == 0
     jump(i6, i4, descr=<Loop0>)
     """
 
-    def test_parse_no_namespace(self):
-        loop = self.parse(self.example_loop_log, no_namespace=True)
-
     def test_attach_comment_to_loop(self):
-        loop = self.parse(self.example_loop_log, no_namespace=True)
+        py.test.skip("failargs")
+        loop = self.parse(self.example_loop_log, guards_with_failargs=True)
         assert loop.comment == '    # bridge out of Guard12, 6 ops'
 
     def test_parse_new_with_comma(self):
         loop = self.parse(x)
         assert loop.operations[0].getopname() == 'new'
 
-    def test_no_fail_args(self):
-        x = '''
-        [i0]
-        guard_true(i0, descr=<Guard0>)
-        '''
-        loop = self.parse(x, nonstrict=True)
-        assert not loop.operations[0].has_extra("failargs")
-
-    def test_fail_args_invent_snapshot(self):
-        def f(op, oparser):
-            op.set_rd_snapshot(['foo'])
-        
-        x = '''
-        [i0]
-        guard_true(i0, descr=<Guard0>) [i0]
-        '''
-        loop = self.parse(x, process_guard=f)
-        assert loop.operations[0].get_rd_snapshot() == ['foo']
-
     def test_results(self):
         x = '''
         [i0]
         assert loop.operations[0].getint() == 13
         assert loop.operations[1].getint() == 12
 
-    def test_no_inputargs(self):
-        x = '''
-        i2 = int_add(i0, i1)
-        '''
-        loop = self.parse(x, nonstrict=True)
-        assert loop.inputargs == []
-        assert loop.operations[0].getopname() == 'int_add'
-
     def test_offsets(self):
         x = """
         [i0, i1]
 
     OpParser = OpParser
 
-    def test_boxkind(self):
-        py.test.skip("what's that?")
-        x = """
-        [sum0]
-        """
-        loop = self.parse(x, None, {}, boxkinds={'sum': BoxInt})
-        b = loop.getboxes()
-        assert isinstance(b.sum0, BoxInt)
-
     def test_label(self):
         x = """
         [i0]