Esempio n. 1
0
 def test_typeof_constant(self):
     t = StaticTuple(10, EmptyTuple())
     self.assertEqual(typeof(t), StaticTuple[int32, EmptyTuple[()]])
     t2 = StaticTuple(2.0, t)
     self.assertEqual(
         typeof(t2), StaticTuple[float64, StaticTuple[int32,
                                                      EmptyTuple[()]]])
Esempio n. 2
0
def typeof(pyval):
    if pyval:
        types = [typeof(x) for x in pyval]
        if len(set(types)) != 1:
            raise TypeError("Got multiple types for elements, %s" % set(types))
        return List[types[0]]
    else:
        return EmptyList[()]
Esempio n. 3
0
def typeof(pyval):
    if pyval:
        types = [typeof(x) for x in pyval]
        if len(set(types)) != 1:
            raise TypeError("Got multiple types for elements, %s" % set(types))
        return List[types[0]]
    else:
        return EmptyList[()]
Esempio n. 4
0
 def element_type(self):
     if self.hd is None:
         raise TypeError("Cannot compute element type of empty tuple!")
     else:
         type = typeof(self.hd)
         if self.tl is not None:
             type = promote(type, self.tl.element_type())
         return type
Esempio n. 5
0
 def element_type(self):
     if self.hd is None:
         raise TypeError("Cannot compute element type of empty tuple!")
     else:
         type = typeof(self.hd)
         if self.tl is not None:
             type = promote(type, self.tl.element_type())
         return type
Esempio n. 6
0
    def f(context, py_func, f_env, op):
        f, args = op.args

        # Add any potentially remaining values
        remaining = get_remaining_args(py_func, (None,) * len(args))
        consts = [allocate_const(func, env, op, value, typeof(value))
                      for value in remaining]
        op.set_args([f, args + consts])
Esempio n. 7
0
def fill_missing_argtypes(func, argtypes):
    """
    Fill missing argument types from default values.
    """
    from flypy import typeof

    argtypes = tuple(argtypes)
    remaining = get_remaining_args(func, argtypes)
    return argtypes + tuple(typeof(arg) for arg in remaining)
Esempio n. 8
0
def fill_missing_argtypes(func, argtypes):
    """
    Fill missing argument types from default values.
    """
    from flypy import typeof

    argtypes = tuple(argtypes)
    remaining = get_remaining_args(func, argtypes)
    return argtypes + tuple(typeof(arg) for arg in remaining)
Esempio n. 9
0
    def f(context, py_func, f_env, op):
        f, args = op.args

        # Add any potentially remaining values
        remaining = get_remaining_args(py_func, (None, ) * len(args))
        consts = [
            allocate_const(func, env, op, value, typeof(value))
            for value in remaining
        ]
        op.set_args([f, args + consts])
Esempio n. 10
0
def extern(name, ffiobj):
    """Creates an ExternalSymbol object and bind CFFI value to the default
    target "cpu".
    """
    # Get type
    foreignfunc = typeof(ffiobj)
    functy = coretypes.Function[foreignfunc.parameters]
    functy.varargs = foreignfunc.varargs
    # Get pointer
    ptr = cffi_support.get_pointer(ffiobj)

    return ExternalSymbol(name, functy, ptr)
Esempio n. 11
0
    def test_representation(self):
        "ctypes"
        ty = typeof((1, 2, 3))
        obj = fromobject((1, 2, 3), ty)
        keepalive = []
        rep = toctypes(obj, ty, keepalive)
        rep = CTypesStruct(rep)

        # print(rep) -> { tl:{ tl:{ tl:{ dummy:0 }, hd:3 }, hd:2 }, hd:1 }
        self.assertEqual(rep.hd, 1)
        self.assertEqual(rep.tl.hd, 2)
        self.assertEqual(rep.tl.tl.hd, 3)
Esempio n. 12
0
def extern(name, ffiobj):
    """Creates an ExternalSymbol object and bind CFFI value to the default
    target "cpu".
    """
    # Get type
    foreignfunc = typeof(ffiobj)
    functy = coretypes.Function[foreignfunc.parameters]
    functy.varargs = foreignfunc.varargs
    # Get pointer
    ptr = cffi_support.get_pointer(ffiobj)

    return ExternalSymbol(name, functy, ptr)
Esempio n. 13
0
    def test_representation(self):
        "ctypes"
        ty = typeof((1, 2, 3))
        obj = fromobject((1, 2, 3), ty)
        keepalive = []
        rep = toctypes(obj, ty, keepalive)
        rep = CTypesStruct(rep)

        # print(rep) -> { tl:{ tl:{ tl:{ dummy:0 }, hd:3 }, hd:2 }, hd:1 }
        self.assertEqual(rep.hd, 1)
        self.assertEqual(rep.tl.hd, 2)
        self.assertEqual(rep.tl.tl.hd, 3)
Esempio n. 14
0
def interpret(nb_func, run_phase, args, debug=False, tracer=None):
    """Interpret and return result"""
    # Translate flypy function
    argtypes = [typeof(arg) for arg in args]
    env = environment.fresh_env(nb_func, argtypes, target="cpu")
    f, env = run_phase(nb_func, env)

    if debug:
        header(f)

    if tracer is None:
        # Set up tracer to trace interpretation
        if debug:
            tracer = tracing.Tracer()
        else:
            tracer = tracing.DummyTracer()

    newargs = [conversion.fromobject(arg, typeof(arg)) for arg in args]

    # Interpret function
    env.setdefault('interp.handlers', handlers(run_phase, env))
    return interp.run(f, env, args=newargs, tracer=tracer)
Esempio n. 15
0
def interpret(nb_func, run_phase, args, debug=False, tracer=None):
    """Interpret and return result"""
    # Translate flypy function
    argtypes = [typeof(arg) for arg in args]
    env = environment.fresh_env(nb_func, argtypes, target="cpu")
    f, env = run_phase(nb_func, env)

    if debug:
        header(f)

    if tracer is None:
        # Set up tracer to trace interpretation
        if debug:
            tracer = tracing.Tracer()
        else:
            tracer = tracing.DummyTracer()

    newargs = [conversion.fromobject(arg, typeof(arg)) for arg in args]

    # Interpret function
    env.setdefault('interp.handlers', handlers(run_phase, env))
    return interp.run(f, env, args=newargs, tracer=tracer)
Esempio n. 16
0
def op_call(run_phase, typeof_func, interp, func, args):
    """
    Called by the interpreter to interpret IR function calls.
    """
    if isinstance(func, Method):
        func, self = func
        args = [self] + list(args)

    if isinstance(func, functionwrapper.FunctionWrapper):
        wrapper = func
        op = interp.op

        try:
            # Flatten args (consider default values)
            args = simple_flatargs(func.py_func, tuple(args), {})
        except TypeError:
            pass

        # Determine argument types
        argtypes = [
            typeof_func(arg, val) for arg, val in zip(op.args[1], args)
        ]

        # Use regular typeof() for remaining arguments (default values)
        remaining_args = args[len(argtypes):]
        for arg in remaining_args:
            argtypes.append(typeof(arg))

        # Compile function
        env = environment.fresh_env(func, argtypes, "cpu")

        if wrapper.opaque and run_phase == phase.frontend:
            func = implement(wrapper, wrapper.py_func, tuple(argtypes), env)
        else:
            func, env = run_phase(func, env)

    elif is_flypy_type(func):
        obj = func(*args)
        return obj
        #layout = type(obj).layout
        #return { 'value': dict((name, getattr(obj, name)) for name in layout) }

    return interp.call(func, args)
Esempio n. 17
0
def make_applier(f, *subterms):
    """Create a blaze function application term"""
    @jit('Apply[subterms]')
    class Apply(object):
        """Function application term"""

        layout = [('subterms', 'subterms')]  # Tuple of sub-expressions

        @jit
        def apply(self, args):
            args = eval_subterms(self.subterms, args)
            return f(*args)

        def __repr__(self):
            return "Apply(%s, %s)" % (f.py_func.__name__, self.subterms)

    # NOTE: flypy doesn't reconstruct flypy objects recursively, it only
    #       acts on roots!
    subterms = fromobject(subterms, typeof(subterms))
    return Apply(subterms)
Esempio n. 18
0
def op_call(run_phase, typeof_func, interp, func, args):
    """
    Called by the interpreter to interpret IR function calls.
    """
    if isinstance(func, Method):
        func, self = func
        args = [self] + list(args)

    if isinstance(func, functionwrapper.FunctionWrapper):
        wrapper = func
        op = interp.op

        try:
            # Flatten args (consider default values)
            args = simple_flatargs(func.py_func, tuple(args), {})
        except TypeError:
            pass

        # Determine argument types
        argtypes = [typeof_func(arg, val) for arg, val in zip(op.args[1], args)]

        # Use regular typeof() for remaining arguments (default values)
        remaining_args = args[len(argtypes):]
        for arg in remaining_args:
            argtypes.append(typeof(arg))

        # Compile function
        env = environment.fresh_env(func, argtypes, "cpu")

        if wrapper.opaque and run_phase == phase.frontend:
            func = implement(wrapper, wrapper.py_func, tuple(argtypes), env)
        else:
            func, env = run_phase(func, env)

    elif is_flypy_type(func):
        obj = func(*args)
        return obj
        #layout = type(obj).layout
        #return { 'value': dict((name, getattr(obj, name)) for name in layout) }

    return interp.call(func, args)
Esempio n. 19
0
def make_applier(f, *subterms):
    """Create a blaze function application term"""

    @jit('Apply[subterms]')
    class Apply(object):
        """Function application term"""

        layout = [('subterms', 'subterms')] # Tuple of sub-expressions

        @jit
        def apply(self, args):
            args = eval_subterms(self.subterms, args)
            return f(*args)

        def __repr__(self):
            return "Apply(%s, %s)" % (f.py_func.__name__, self.subterms)

    # NOTE: flypy doesn't reconstruct flypy objects recursively, it only
    #       acts on roots!
    subterms = fromobject(subterms, typeof(subterms))
    return Apply(subterms)
Esempio n. 20
0
def initial_context(func):
    """Initialize context with argtypes"""
    context = { 'return': set(), 'generator': set(), void: void, bool_: bool_ }
    context['return'] = set()
    count = 0

    for op in func.ops:
        context[op] = set()
        if op.opcode == 'alloca':
            context['alloca%d' % count] = set()
            count += 1
        for arg in flatten(op.args):
            if (isinstance(arg, ir.Const) and
                    isinstance(arg.const, FunctionWrapper)):
                context[arg] = set([None])
            elif isinstance(arg, ir.Const):
                context[arg] = set([typeof(arg.const)])
            elif isinstance(arg, ir.Undef):
                context[arg] = set()
            elif isinstance(arg, ir.GlobalValue):
                raise NotImplementedError("Globals")

    return context
Esempio n. 21
0
 def f(x):
     return typeof(x)
Esempio n. 22
0
 def typeof_untyped(self, arg, argval):
     return typeof(argval)
Esempio n. 23
0
 def test_typeof(self):
     self.assertEqual(typeof(StopIteration()),
                      exceptions.StopIteration.type)
Esempio n. 24
0
 def test_typeof(self):
     self.assertEqual(typeof(StopIteration()), exceptions.StopIteration.type)
Esempio n. 25
0
def to_flypy(tup):
    return fromobject(tup, typeof(tup))
Esempio n. 26
0
 def f():
     obj = C(False)
     restype = typeof(obj.method())
     return obj.ran, restype
Esempio n. 27
0
def topy(tup):
    return toobject(tup, typeof(tup))
Esempio n. 28
0
 def typeof_untyped(self, arg, argval):
     return typeof(argval)
Esempio n. 29
0
 def test_typeof_constant(self):
     t = StaticTuple(10, EmptyTuple())
     self.assertEqual(typeof(t), StaticTuple[int32, EmptyTuple[()]])
     t2 = StaticTuple(2.0, t)
     self.assertEqual(typeof(t2), StaticTuple[float64, StaticTuple[int32, EmptyTuple[()]]])
Esempio n. 30
0
def tonb(tup):
    return fromobject(tup, typeof(tup))
Esempio n. 31
0
def tonb(tup):
    return fromobject(tup, typeof(tup))
Esempio n. 32
0
 def test_typeof(self):
     "typeof"
     self.assertEqual(typeof((10, 20)),
                      StaticTuple[int32, StaticTuple[int32, EmptyTuple[()]]])
Esempio n. 33
0
def topy(tup):
    return toobject(tup, typeof(tup))
Esempio n. 34
0
 def test_typeof(self):
     "typeof"
     self.assertEqual(
         typeof((10, 20)), StaticTuple[int32, StaticTuple[int32,
                                                          EmptyTuple[()]]])
Esempio n. 35
0
class _Decimal(object):
    layout = [('mpd', Pointer[typeof(mpd_t)])]
    
    @jit
    def __init__(self, mpd):
        
        #print('__init__')
        self.mpd = mpd

    @jit
    def __del__(self):
        
        #print('__del__')
        mpd_del_func(self.mpd)

    @jit
    def __repr__(self):
       
        return 'Decimal'

    @jit
    def __str__(self):
        
        return from_cstring(mpd_to_sci_func(self.mpd, 0))

    @jit
    def __add__(self, right):
        
        mpd_result = mpd_new_func()
        mpd_add_func(mpd_result, self.mpd, right.mpd, context_ref)
        return _Decimal(mpd_result)

    @jit
    def __sub__(self, right):
        
        mpd_result = mpd_new_func()
        mpd_sub_func(mpd_result, self.mpd, right.mpd, context_ref)
        return _Decimal(mpd_result)

    @jit
    def __mul__(self, right):
        mpd_result = mpd_new_func()
        mpd_mul_func(mpd_result, self.mpd, right.mpd, context_ref)
        return _Decimal(mpd_result)

    @jit
    def __lt__(self, right):
        mpd_temp = mpd_new_func()
        result = mpd_cmp_func(mpd_temp, self.mpd, right.mpd, context_ref)
        mpd_del_func(mpd_temp)
        if result == -1:
            return True
        return False

    @jit
    def __gt__(self, right):
        mpd_temp = mpd_new_func()
        result = mpd_cmp_func(mpd_temp, self.mpd, right.mpd, context_ref)
        mpd_del_func(mpd_temp)
        if result == 1:
            return True
        return False