Shadow.py 11.4 KB
Newer Older
Robert Bradshaw's avatar
Robert Bradshaw committed
1
# cython.* namespace for pure mode.
2
__version__ = "0.23dev"
Robert Bradshaw's avatar
Robert Bradshaw committed
3

4 5

# BEGIN shameless copy from Cython/minivect/minitypes.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

class _ArrayType(object):

    is_array = True
    subtypes = ['dtype']

    def __init__(self, dtype, ndim, is_c_contig=False, is_f_contig=False,
                 inner_contig=False, broadcasting=None):
        self.dtype = dtype
        self.ndim = ndim
        self.is_c_contig = is_c_contig
        self.is_f_contig = is_f_contig
        self.inner_contig = inner_contig or is_c_contig or is_f_contig
        self.broadcasting = broadcasting

    def __repr__(self):
        axes = [":"] * self.ndim
        if self.is_c_contig:
            axes[-1] = "::1"
        elif self.is_f_contig:
            axes[0] = "::1"

        return "%s[%s]" % (self.dtype, ", ".join(axes))

30

31 32 33 34 35 36
def index_type(base_type, item):
    """
    Support array type creation by slicing, e.g. double[:, :] specifies
    a 2D strided array of doubles. The syntax is the same as for
    Cython memoryviews.
    """
37 38 39
    class InvalidTypeSpecification(Exception):
        pass

40 41
    def verify_slice(s):
        if s.start or s.stop or s.step not in (None, 1):
42
            raise InvalidTypeSpecification(
43 44 45 46 47 48 49 50
                "Only a step of 1 may be provided to indicate C or "
                "Fortran contiguity")

    if isinstance(item, tuple):
        step_idx = None
        for idx, s in enumerate(item):
            verify_slice(s)
            if s.step and (step_idx or idx not in (0, len(item) - 1)):
51
                raise InvalidTypeSpecification(
52 53 54 55 56 57 58 59 60
                    "Step may only be provided once, and only in the "
                    "first or last dimension.")

            if s.step == 1:
                step_idx = idx

        return _ArrayType(base_type, len(item),
                          is_c_contig=step_idx == len(item) - 1,
                          is_f_contig=step_idx == 0)
61
    elif isinstance(item, slice):
62 63
        verify_slice(item)
        return _ArrayType(base_type, 1, is_c_contig=bool(item.step))
64 65
    else:
        # int[8] etc.
66
        assert int(item) == item  # array size must be a plain integer
67
        array(base_type, item)
68 69 70

# END shameless copy

71

72 73
compiled = False

74
_Unspecified = object()
75

Robert Bradshaw's avatar
Robert Bradshaw committed
76 77
# Function decorators

78 79 80
def _empty_decorator(x):
    return x

81
def locals(**arg_types):
82 83
    return _empty_decorator

84
def test_assert_path_exists(*paths):
85 86
    return _empty_decorator

87
def test_fail_if_path_exists(*paths):
88 89
    return _empty_decorator

90 91 92 93 94 95 96
class _EmptyDecoratorAndManager(object):
    def __call__(self, x):
        return x
    def __enter__(self):
        pass
    def __exit__(self, exc_type, exc_value, traceback):
        pass
97

Haoyu Bai's avatar
Haoyu Bai committed
98
cclass = ccall = cfunc = _EmptyDecoratorAndManager()
Haoyu Bai's avatar
Haoyu Bai committed
99

100
returns = wraparound = boundscheck = profile = freelist = lambda arg: _EmptyDecoratorAndManager()
101

102
final = internal = type_version_tag = no_gc_clear = _empty_decorator
103

Robert Bradshaw's avatar
Robert Bradshaw committed
104 105 106 107 108 109 110 111
def inline(f, *args, **kwds):
  if isinstance(f, basestring):
    from Cython.Build.Inline import cython_inline
    return cython_inline(f, *args, **kwds)
  else:
    assert len(args) == len(kwds) == 0
    return f

Robert Bradshaw's avatar
Robert Bradshaw committed
112 113 114 115
def compile(f):
    from Cython.Build.Inline import RuntimeCompiledFunction
    return RuntimeCompiledFunction(f)

Robert Bradshaw's avatar
Robert Bradshaw committed
116 117 118 119 120 121 122 123 124 125 126 127 128
# Special functions

def cdiv(a, b):
    q = a / b
    if q < 0:
        q += 1

def cmod(a, b):
    r = a % b
    if (a*b) < 0:
        r -= b
    return r

129 130 131

# Emulated language constructs

132
def cast(type, *args):
133
    if hasattr(type, '__call__'):
134
        return type(*args)
135
    else:
136
        return args[0]
137

138 139
def sizeof(arg):
    return 1
140 141

def typeof(arg):
142 143
    return arg.__class__.__name__
    # return type(arg)
144

145 146
def address(arg):
    return pointer(type(arg))([arg])
147

148
def declare(type=None, value=_Unspecified, **kwds):
149
    if type not in (None, object) and hasattr(type, '__call__'):
150
        if value is not _Unspecified:
Robert Bradshaw's avatar
Robert Bradshaw committed
151 152 153
            return type(value)
        else:
            return type()
154
    else:
Robert Bradshaw's avatar
Robert Bradshaw committed
155
        return value
156

157 158 159 160 161 162 163 164 165
class _nogil(object):
    """Support for 'with nogil' statement
    """
    def __enter__(self):
        pass
    def __exit__(self, exc_class, exc, tb):
        return exc_class is None

nogil = _nogil()
Mark Florisson's avatar
Mark Florisson committed
166
gil = _nogil()
167 168
del _nogil

169 170
# Emulated types

171 172 173 174 175 176 177 178
class CythonMetaType(type):

    def __getitem__(type, ix):
        return array(type, ix)

CythonTypeObject = CythonMetaType('CythonTypeObject', (object,), {})

class CythonType(CythonTypeObject):
179 180 181 182 183 184 185 186 187

    def _pointer(self, n=1):
        for i in range(n):
            self = pointer(self)
        return self

class PointerType(CythonType):

    def __init__(self, value=None):
188
        if isinstance(value, (ArrayType, PointerType)):
189 190 191
            self._items = [cast(self._basetype, a) for a in value._items]
        elif isinstance(value, list):
            self._items = [cast(self._basetype, a) for a in value]
192
        elif value is None or value == 0:
193 194 195
            self._items = []
        else:
            raise ValueError
196

197 198
    def __getitem__(self, ix):
        if ix < 0:
199
            raise IndexError("negative indexing not allowed in C")
200
        return self._items[ix]
201

202 203
    def __setitem__(self, ix, value):
        if ix < 0:
204
            raise IndexError("negative indexing not allowed in C")
205
        self._items[ix] = cast(self._basetype, value)
206

207 208 209 210 211 212
    def __eq__(self, value):
        if value is None and not self._items:
            return True
        elif type(self) != type(value):
            return False
        else:
Robert Bradshaw's avatar
Robert Bradshaw committed
213
            return not self._items and not value._items
214

215 216 217
    def __repr__(self):
        return "%s *" % (self._basetype,)

218
class ArrayType(PointerType):
219

220 221 222 223 224
    def __init__(self):
        self._items = [None] * self._n


class StructType(CythonType):
225

226 227 228 229 230 231 232 233 234 235 236 237
    def __init__(self, cast_from=_Unspecified, **data):
        if cast_from is not _Unspecified:
            # do cast
            if len(data) > 0:
                raise ValueError('Cannot accept keyword arguments when casting.')
            if type(cast_from) is not type(self):
                raise ValueError('Cannot cast from %s'%cast_from)
            for key, value in cast_from.__dict__.items():
                setattr(self, key, value)
        else:
            for key, value in data.iteritems():
                setattr(self, key, value)
238

239 240 241 242
    def __setattr__(self, key, value):
        if key in self._members:
            self.__dict__[key] = cast(self._members[key], value)
        else:
243
            raise AttributeError("Struct has no member '%s'" % key)
244

245 246 247

class UnionType(CythonType):

248 249 250 251 252 253 254 255 256 257 258 259 260 261
    def __init__(self, cast_from=_Unspecified, **data):
        if cast_from is not _Unspecified:
            # do type cast
            if len(data) > 0:
                raise ValueError('Cannot accept keyword arguments when casting.')
            if isinstance(cast_from, dict):
                datadict = cast_from
            elif type(cast_from) is type(self):
                datadict = cast_from.__dict__
            else:
                raise ValueError('Cannot cast from %s'%cast_from)
        else:
            datadict = data
        if len(datadict) > 1:
262
            raise AttributeError("Union can only store one field at a time.")
263
        for key, value in datadict.iteritems():
264
            setattr(self, key, value)
265

266 267 268 269 270 271
    def __setattr__(self, key, value):
        if key in '__dict__':
            CythonType.__setattr__(self, key, value)
        elif key in self._members:
            self.__dict__ = {key: cast(self._members[key], value)}
        else:
272
            raise AttributeError("Union has no member '%s'" % key)
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

def pointer(basetype):
    class PointerInstance(PointerType):
        _basetype = basetype
    return PointerInstance

def array(basetype, n):
    class ArrayInstance(ArrayType):
        _basetype = basetype
        _n = n
    return ArrayInstance

def struct(**members):
    class StructInstance(StructType):
        _members = members
288
    for key in members:
289 290 291 292 293 294
        setattr(StructInstance, key, None)
    return StructInstance

def union(**members):
    class UnionInstance(UnionType):
        _members = members
295
    for key in members:
296 297 298 299 300
        setattr(UnionInstance, key, None)
    return UnionInstance

class typedef(CythonType):

301
    def __init__(self, type, name=None):
302
        self._basetype = type
303
        self.name = name
304

305 306
    def __call__(self, *arg):
        value = cast(self._basetype, *arg)
307
        return value
308

309 310 311
    def __repr__(self):
        return self.name or str(self._basetype)

312 313
    __getitem__ = index_type

314
class _FusedType(CythonType):
315
    pass
316 317 318 319 320 321


def fused_type(*args):
    if not args:
        raise TypeError("Expected at least one type as argument")

322
    # Find the numeric type with biggest rank if all types are numeric
323 324 325 326 327 328 329 330 331 332 333 334 335 336
    rank = -1
    for type in args:
        if type not in (py_int, py_long, py_float, py_complex):
            break

        if type_ordering.index(type) > rank:
            result_type = type
    else:
        return result_type

    # Not a simple numeric type, return a fused type instance. The result
    # isn't really meant to be used, as we can't keep track of the context in
    # pure-mode. Casting won't do anything in this case.
    return _FusedType()
337

338

339 340 341 342 343 344
def _specialized_from_args(signatures, args, kwargs):
    "Perhaps this should be implemented in a TreeFragment in Cython code"
    raise Exception("yet to be implemented")


py_int = typedef(int, "int")
345
try:
346
    py_long = typedef(long, "long")
347
except NameError: # Py3
348 349
    py_long = typedef(int, "long")
py_float = typedef(float, "float")
350
py_complex = typedef(complex, "double complex")
351

Robert Bradshaw's avatar
Robert Bradshaw committed
352

353 354
# Predefined types

355
int_types = ['char', 'short', 'Py_UNICODE', 'int', 'Py_UCS4', 'long', 'longlong', 'Py_ssize_t', 'size_t']
356 357
float_types = ['longdouble', 'double', 'float']
complex_types = ['longdoublecomplex', 'doublecomplex', 'floatcomplex', 'complex']
358
other_types = ['bint', 'void']
359

360 361 362 363 364 365 366 367
to_repr = {
    'longlong': 'long long',
    'longdouble': 'long double',
    'longdoublecomplex': 'long double complex',
    'doublecomplex': 'double complex',
    'floatcomplex': 'float complex',
}.get

368 369
gs = globals()

Stefan Behnel's avatar
Stefan Behnel committed
370 371 372 373 374 375 376 377 378
# note: cannot simply name the unicode type here as 2to3 gets in the way and replaces it by str
try:
    import __builtin__ as builtins
except ImportError:  # Py3
    import builtins

gs['unicode'] = typedef(getattr(builtins, 'unicode', str), 'unicode')
del builtins

379
for name in int_types:
380 381
    reprname = to_repr(name, name)
    gs[name] = typedef(py_int, reprname)
382
    if name not in ('Py_UNICODE', 'Py_UCS4') and not name.endswith('size_t'):
383 384
        gs['u'+name] = typedef(py_int, "unsigned " + reprname)
        gs['s'+name] = typedef(py_int, "signed " + reprname)
385

386
for name in float_types:
387
    gs[name] = typedef(py_float, to_repr(name, name))
388 389

for name in complex_types:
390
    gs[name] = typedef(py_complex, to_repr(name, name))
391

392 393
bint = typedef(bool, "bint")
void = typedef(int, "void")
394

395
for t in int_types + float_types + complex_types + other_types:
396 397 398
    for i in range(1, 4):
        gs["%s_%s" % ('p'*i, t)] = globals()[t]._pointer(i)

399
void = typedef(None, "void")
Robert Bradshaw's avatar
Robert Bradshaw committed
400
NULL = p_void(0)
401

402 403 404
integral = floating = numeric = _FusedType()

type_ordering = [py_int, py_long, py_float, py_complex]
405

406 407 408 409 410 411 412
class CythonDotParallel(object):
    """
    The cython.parallel module.
    """

    __all__ = ['parallel', 'prange', 'threadid']

413 414
    def parallel(self, num_threads=None):
        return nogil
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

    def prange(self, start=0, stop=None, step=1, schedule=None, nogil=False):
        if stop is None:
            stop = start
            start = 0
        return range(start, stop, step)

    def threadid(self):
        return 0

    # def threadsavailable(self):
        # return 1

import sys
sys.modules['cython.parallel'] = CythonDotParallel()
430
del sys