Shadow.py 11.5 KB
Newer Older
Robert Bradshaw's avatar
Robert Bradshaw committed
1
# cython.* namespace for pure mode.
2 3
from __future__ import absolute_import

Stefan Behnel's avatar
Stefan Behnel committed
4
__version__ = "0.23.2"
Robert Bradshaw's avatar
Robert Bradshaw committed
5

6 7 8 9 10
try:
    from __builtin__ import basestring
except ImportError:
    basestring = str

11 12

# BEGIN shameless copy from Cython/minivect/minitypes.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

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))

37

38 39 40 41 42 43
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.
    """
44 45 46
    class InvalidTypeSpecification(Exception):
        pass

47 48
    def verify_slice(s):
        if s.start or s.stop or s.step not in (None, 1):
49
            raise InvalidTypeSpecification(
50 51 52 53 54 55 56 57
                "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)):
58
                raise InvalidTypeSpecification(
59 60 61 62 63 64 65 66 67
                    "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)
68
    elif isinstance(item, slice):
69 70
        verify_slice(item)
        return _ArrayType(base_type, 1, is_c_contig=bool(item.step))
71 72
    else:
        # int[8] etc.
73
        assert int(item) == item  # array size must be a plain integer
74
        array(base_type, item)
75 76 77

# END shameless copy

78

79 80
compiled = False

81
_Unspecified = object()
82

Robert Bradshaw's avatar
Robert Bradshaw committed
83 84
# Function decorators

85 86 87
def _empty_decorator(x):
    return x

88
def locals(**arg_types):
89 90
    return _empty_decorator

91
def test_assert_path_exists(*paths):
92 93
    return _empty_decorator

94
def test_fail_if_path_exists(*paths):
95 96
    return _empty_decorator

97 98 99 100 101 102 103
class _EmptyDecoratorAndManager(object):
    def __call__(self, x):
        return x
    def __enter__(self):
        pass
    def __exit__(self, exc_type, exc_value, traceback):
        pass
104

Haoyu Bai's avatar
Haoyu Bai committed
105
cclass = ccall = cfunc = _EmptyDecoratorAndManager()
Haoyu Bai's avatar
Haoyu Bai committed
106

107
returns = wraparound = boundscheck = profile = freelist = lambda arg: _EmptyDecoratorAndManager()
108

109
final = internal = type_version_tag = no_gc_clear = _empty_decorator
110

Robert Bradshaw's avatar
Robert Bradshaw committed
111 112 113 114 115 116 117 118
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
119 120 121 122
def compile(f):
    from Cython.Build.Inline import RuntimeCompiledFunction
    return RuntimeCompiledFunction(f)

Robert Bradshaw's avatar
Robert Bradshaw committed
123 124 125 126 127 128 129 130 131 132 133 134 135
# 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

136 137 138

# Emulated language constructs

139
def cast(type, *args):
140
    if hasattr(type, '__call__'):
141
        return type(*args)
142
    else:
143
        return args[0]
144

145 146
def sizeof(arg):
    return 1
147 148

def typeof(arg):
149 150
    return arg.__class__.__name__
    # return type(arg)
151

152 153
def address(arg):
    return pointer(type(arg))([arg])
154

155
def declare(type=None, value=_Unspecified, **kwds):
156
    if type not in (None, object) and hasattr(type, '__call__'):
157
        if value is not _Unspecified:
Robert Bradshaw's avatar
Robert Bradshaw committed
158 159 160
            return type(value)
        else:
            return type()
161
    else:
Robert Bradshaw's avatar
Robert Bradshaw committed
162
        return value
163

164 165 166 167 168 169 170 171 172
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
173
gil = _nogil()
174 175
del _nogil

176 177
# Emulated types

178 179 180 181 182 183 184 185
class CythonMetaType(type):

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

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

class CythonType(CythonTypeObject):
186 187 188 189 190 191 192 193 194

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

class PointerType(CythonType):

    def __init__(self, value=None):
195
        if isinstance(value, (ArrayType, PointerType)):
196 197 198
            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]
199
        elif value is None or value == 0:
200 201 202
            self._items = []
        else:
            raise ValueError
203

204 205
    def __getitem__(self, ix):
        if ix < 0:
206
            raise IndexError("negative indexing not allowed in C")
207
        return self._items[ix]
208

209 210
    def __setitem__(self, ix, value):
        if ix < 0:
211
            raise IndexError("negative indexing not allowed in C")
212
        self._items[ix] = cast(self._basetype, value)
213

214 215 216 217 218 219
    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
220
            return not self._items and not value._items
221

222 223 224
    def __repr__(self):
        return "%s *" % (self._basetype,)

225
class ArrayType(PointerType):
226

227 228 229 230 231
    def __init__(self):
        self._items = [None] * self._n


class StructType(CythonType):
232

233 234 235 236 237 238 239 240 241 242
    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:
243
            for key, value in data.items():
244
                setattr(self, key, value)
245

246 247 248 249
    def __setattr__(self, key, value):
        if key in self._members:
            self.__dict__[key] = cast(self._members[key], value)
        else:
250
            raise AttributeError("Struct has no member '%s'" % key)
251

252 253 254

class UnionType(CythonType):

255 256 257 258 259 260 261 262 263 264 265 266 267 268
    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:
269
            raise AttributeError("Union can only store one field at a time.")
270
        for key, value in datadict.items():
271
            setattr(self, key, value)
272

273 274 275 276 277 278
    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:
279
            raise AttributeError("Union has no member '%s'" % key)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

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
295
    for key in members:
296 297 298 299 300 301
        setattr(StructInstance, key, None)
    return StructInstance

def union(**members):
    class UnionInstance(UnionType):
        _members = members
302
    for key in members:
303 304 305 306 307
        setattr(UnionInstance, key, None)
    return UnionInstance

class typedef(CythonType):

308
    def __init__(self, type, name=None):
309
        self._basetype = type
310
        self.name = name
311

312 313
    def __call__(self, *arg):
        value = cast(self._basetype, *arg)
314
        return value
315

316 317 318
    def __repr__(self):
        return self.name or str(self._basetype)

319 320
    __getitem__ = index_type

321
class _FusedType(CythonType):
322
    pass
323 324 325 326 327 328


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

329
    # Find the numeric type with biggest rank if all types are numeric
330 331 332 333 334 335 336 337 338 339 340 341 342 343
    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()
344

345

346 347 348 349 350 351
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")
352
try:
353
    py_long = typedef(long, "long")
354
except NameError:  # Py3
355 356
    py_long = typedef(int, "long")
py_float = typedef(float, "float")
357
py_complex = typedef(complex, "double complex")
358

Robert Bradshaw's avatar
Robert Bradshaw committed
359

360 361
# Predefined types

362
int_types = ['char', 'short', 'Py_UNICODE', 'int', 'Py_UCS4', 'long', 'longlong', 'Py_ssize_t', 'size_t']
363 364
float_types = ['longdouble', 'double', 'float']
complex_types = ['longdoublecomplex', 'doublecomplex', 'floatcomplex', 'complex']
365
other_types = ['bint', 'void']
366

367 368 369 370 371 372 373 374
to_repr = {
    'longlong': 'long long',
    'longdouble': 'long double',
    'longdoublecomplex': 'long double complex',
    'doublecomplex': 'double complex',
    'floatcomplex': 'float complex',
}.get

375 376
gs = globals()

Stefan Behnel's avatar
Stefan Behnel committed
377 378 379 380 381 382 383 384 385
# 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

386
for name in int_types:
387 388
    reprname = to_repr(name, name)
    gs[name] = typedef(py_int, reprname)
389
    if name not in ('Py_UNICODE', 'Py_UCS4') and not name.endswith('size_t'):
390 391
        gs['u'+name] = typedef(py_int, "unsigned " + reprname)
        gs['s'+name] = typedef(py_int, "signed " + reprname)
392

393
for name in float_types:
394
    gs[name] = typedef(py_float, to_repr(name, name))
395 396

for name in complex_types:
397
    gs[name] = typedef(py_complex, to_repr(name, name))
398

399 400
bint = typedef(bool, "bint")
void = typedef(int, "void")
401

402
for t in int_types + float_types + complex_types + other_types:
403 404 405
    for i in range(1, 4):
        gs["%s_%s" % ('p'*i, t)] = globals()[t]._pointer(i)

406
void = typedef(None, "void")
Robert Bradshaw's avatar
Robert Bradshaw committed
407
NULL = p_void(0)
408

409 410 411
integral = floating = numeric = _FusedType()

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

413 414 415 416 417 418 419
class CythonDotParallel(object):
    """
    The cython.parallel module.
    """

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

420 421
    def parallel(self, num_threads=None):
        return nogil
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

    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()
437
del sys