Python 2.3 fix.
[cython.git] / Cython / Shadow.py
1 # cython.* namespace for pure mode.
2
3 compiled = False
4
5 def empty_decorator(x):
6     return x
7
8 # Function decorators
9
10 def locals(**arg_types):
11     return empty_decorator
12
13 def inline(f, *args, **kwds):
14   if isinstance(f, basestring):
15     from Cython.Build.Inline import cython_inline
16     return cython_inline(f, *args, **kwds)
17   else:
18     assert len(args) == len(kwds) == 0
19     return f
20
21 def compile(f):
22     from Cython.Build.Inline import RuntimeCompiledFunction
23     return RuntimeCompiledFunction(f)
24
25 # Special functions
26
27 def cdiv(a, b):
28     q = a / b
29     if q < 0:
30         q += 1
31
32 def cmod(a, b):
33     r = a % b
34     if (a*b) < 0:
35         r -= b
36     return r
37
38
39 # Emulated language constructs
40
41 def cast(type, arg):
42     if hasattr(type, '__call__'):
43         return type(arg)
44     else:
45         return arg
46
47 def sizeof(arg):
48     return 1
49
50 def typeof(arg):
51     return type(arg)
52     
53 def address(arg):
54     return pointer(type(arg))([arg])
55     
56 def declare(type=None, value=None, **kwds):
57     if type is not None and hasattr(type, '__call__'):
58         if value:
59             return type(value)
60         else:
61             return type()
62     else:
63         return value
64
65 class _nogil(object):
66     """Support for 'with nogil' statement
67     """
68     def __enter__(self):
69         pass
70     def __exit__(self, exc_class, exc, tb):
71         return exc_class is None
72
73 nogil = _nogil()
74 del _nogil
75
76 # Emulated types
77
78 class CythonType(object):
79
80     def _pointer(self, n=1):
81         for i in range(n):
82             self = pointer(self)
83         return self
84
85     def __getitem__(self, ix):
86         return array(self, ix)
87
88
89 class PointerType(CythonType):
90
91     def __init__(self, value=None):
92         if isinstance(value, ArrayType):
93             self._items = [cast(self._basetype, a) for a in value._items]
94         elif isinstance(value, list):
95             self._items = [cast(self._basetype, a) for a in value]
96         elif value is None:
97             self._items = []
98         else:
99             raise ValueError
100             
101     def __getitem__(self, ix):
102         if ix < 0:
103             raise IndexError("negative indexing not allowed in C")
104         return self._items[ix]
105         
106     def __setitem__(self, ix, value):
107         if ix < 0:
108             raise IndexError("negative indexing not allowed in C")
109         self._items[ix] = cast(self._basetype, value)
110         
111 class ArrayType(PointerType):
112     
113     def __init__(self):
114         self._items = [None] * self._n
115
116
117 class StructType(CythonType):
118     
119     def __init__(self, **data):
120         for key, value in data.iteritems():
121             setattr(self, key, value)
122             
123     def __setattr__(self, key, value):
124         if key in self._members:
125             self.__dict__[key] = cast(self._members[key], value)
126         else:
127             raise AttributeError("Struct has no member '%s'" % key)
128     
129
130 class UnionType(CythonType):
131
132     def __init__(self, **data):
133         if len(data) > 0:
134             raise AttributeError("Union can only store one field at a time.")
135         for key, value in data.iteritems():
136             setattr(self, key, value)
137             
138     def __setattr__(self, key, value):
139         if key in '__dict__':
140             CythonType.__setattr__(self, key, value)
141         elif key in self._members:
142             self.__dict__ = {key: cast(self._members[key], value)}
143         else:
144             raise AttributeError("Union has no member '%s'" % key)
145
146 def pointer(basetype):
147     class PointerInstance(PointerType):
148         _basetype = basetype
149     return PointerInstance
150
151 def array(basetype, n):
152     class ArrayInstance(ArrayType):
153         _basetype = basetype
154         _n = n
155     return ArrayInstance
156
157 def struct(**members):
158     class StructInstance(StructType):
159         _members = members
160     for key in members:
161         setattr(StructInstance, key, None)
162     return StructInstance
163
164 def union(**members):
165     class UnionInstance(UnionType):
166         _members = members
167     for key in members:
168         setattr(UnionInstance, key, None)
169     return UnionInstance
170
171 class typedef(CythonType):
172
173     def __init__(self, type):
174         self._basetype = type
175     
176     def __call__(self, value=None):
177         if value is not None:
178             value = cast(self._basetype, value)
179         return value
180         
181
182
183 py_int = int
184 try:
185     py_long = long
186 except NameError: # Py3
187     py_long = int
188 py_float = float
189 py_complex = complex
190
191
192 try:
193     set
194 except NameError:
195     # Python 2.3
196     from sets import Set as set, ImmutableSet as frozenset
197
198 # Predefined types
199
200 int_types = ['char', 'short', 'Py_UNICODE', 'int', 'long', 'longlong', 'Py_ssize_t', 'size_t']
201 float_types = ['longdouble', 'double', 'float']
202 complex_types = ['longdoublecomplex', 'doublecomplex', 'floatcomplex', 'complex']
203 other_types = ['bint', 'void']
204
205 gs = globals()
206
207 for name in int_types:
208     gs[name] = typedef(py_int)
209     if name != 'Py_UNICODE' and not name.endswith('size_t'):
210         gs['u'+name] = typedef(py_int)
211         gs['s'+name] = typedef(py_int)
212     
213 for name in float_types:
214     gs[name] = typedef(py_float)
215
216 for name in complex_types:
217     gs[name] = typedef(py_complex)
218
219 bint = typedef(bool)
220 void = typedef(int)
221
222 for t in int_types + float_types + complex_types + other_types:
223     for i in range(1, 4):
224         gs["%s_%s" % ('p'*i, t)] = globals()[t]._pointer(i)
225
226 void = typedef(None)
227 NULL = None