types.py 2.08 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
import sympy as sp
from sympy.core.cache import cacheit


class TypedSymbol(sp.Symbol):

    def __new__(cls, name, *args, **kwds):
        obj = TypedSymbol.__xnew_cached_(cls, name, *args, **kwds)
        return obj

    def __new_stage2__(cls, name, dtype):
        obj = super(TypedSymbol, cls).__xnew__(cls, name)
Jan Hoenig's avatar
Jan Hoenig committed
13
        obj._dtype = DataType(dtype) if isinstance(dtype, str) else dtype
14
15
16
17
18
19
20
21
22
23
24
        return obj

    __xnew__ = staticmethod(__new_stage2__)
    __xnew_cached_ = staticmethod(cacheit(__new_stage2__))

    @property
    def dtype(self):
        return self._dtype

    def _hashable_content(self):
        superClassContents = list(super(TypedSymbol, self)._hashable_content())
25
        t = tuple(superClassContents + [hash(repr(self._dtype))])
26
        return t
27
28
29
30

    def __getnewargs__(self):
        return self.name, self.dtype

31

Jan Hoenig's avatar
Jan Hoenig committed
32
33
_c_dtype_dict = {0: 'bool', 1: 'int', 2: 'float', 3: 'double'}
_dtype_dict = {'bool': 0, 'int': 1, 'float': 2, 'double': 3}
34
35
36
37
38
39


class DataType(object):
    def __init__(self, dtype):
        self.alias = True
        self.const = False
40
        self.ptr = False
Jan Hoenig's avatar
Jan Hoenig committed
41
        self.dtype = 0
42
        if isinstance(dtype, str):
Jan Hoenig's avatar
Jan Hoenig committed
43
44
45
46
47
48
49
50
51
52
53
            for s in dtype.split():
                if s == 'const':
                    self.const = True
                elif s == '*':
                    self.ptr = True
                elif s == '__restrict__':
                    self.alias = False
                else:
                    self.dtype = _dtype_dict[s]
        elif isinstance(dtype, DataType):
            self.__dict__.update(dtype.__dict__)
54
55
56
57
        else:
            self.dtype = dtype

    def __repr__(self):
58
59
        return "{!s} {!s}{!s} {!s}".format("const" if self.const else "", _c_dtype_dict[self.dtype],
                                           "*" if self.ptr else "", "__restrict__" if not self.alias else "")
Jan Hoenig's avatar
Jan Hoenig committed
60
61
62
63
64
65

    def __eq__(self, other):
        if self.alias == other.alias and self.const == other.const and self.ptr == other.ptr and self.dtype == other.dtype:
            return True
        else:
            return False
Jan Hoenig's avatar
Jan Hoenig committed
66
67
68

def get_type_from_sympy(node):
    return DataType('int')