Shadow.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. # cython.* namespace for pure mode.
  2. from __future__ import absolute_import
  3. __version__ = "0.28.2"
  4. try:
  5. from __builtin__ import basestring
  6. except ImportError:
  7. basestring = str
  8. # BEGIN shameless copy from Cython/minivect/minitypes.py
  9. class _ArrayType(object):
  10. is_array = True
  11. subtypes = ['dtype']
  12. def __init__(self, dtype, ndim, is_c_contig=False, is_f_contig=False,
  13. inner_contig=False, broadcasting=None):
  14. self.dtype = dtype
  15. self.ndim = ndim
  16. self.is_c_contig = is_c_contig
  17. self.is_f_contig = is_f_contig
  18. self.inner_contig = inner_contig or is_c_contig or is_f_contig
  19. self.broadcasting = broadcasting
  20. def __repr__(self):
  21. axes = [":"] * self.ndim
  22. if self.is_c_contig:
  23. axes[-1] = "::1"
  24. elif self.is_f_contig:
  25. axes[0] = "::1"
  26. return "%s[%s]" % (self.dtype, ", ".join(axes))
  27. def index_type(base_type, item):
  28. """
  29. Support array type creation by slicing, e.g. double[:, :] specifies
  30. a 2D strided array of doubles. The syntax is the same as for
  31. Cython memoryviews.
  32. """
  33. class InvalidTypeSpecification(Exception):
  34. pass
  35. def verify_slice(s):
  36. if s.start or s.stop or s.step not in (None, 1):
  37. raise InvalidTypeSpecification(
  38. "Only a step of 1 may be provided to indicate C or "
  39. "Fortran contiguity")
  40. if isinstance(item, tuple):
  41. step_idx = None
  42. for idx, s in enumerate(item):
  43. verify_slice(s)
  44. if s.step and (step_idx or idx not in (0, len(item) - 1)):
  45. raise InvalidTypeSpecification(
  46. "Step may only be provided once, and only in the "
  47. "first or last dimension.")
  48. if s.step == 1:
  49. step_idx = idx
  50. return _ArrayType(base_type, len(item),
  51. is_c_contig=step_idx == len(item) - 1,
  52. is_f_contig=step_idx == 0)
  53. elif isinstance(item, slice):
  54. verify_slice(item)
  55. return _ArrayType(base_type, 1, is_c_contig=bool(item.step))
  56. else:
  57. # int[8] etc.
  58. assert int(item) == item # array size must be a plain integer
  59. array(base_type, item)
  60. # END shameless copy
  61. compiled = False
  62. _Unspecified = object()
  63. # Function decorators
  64. def _empty_decorator(x):
  65. return x
  66. def locals(**arg_types):
  67. return _empty_decorator
  68. def test_assert_path_exists(*paths):
  69. return _empty_decorator
  70. def test_fail_if_path_exists(*paths):
  71. return _empty_decorator
  72. class _EmptyDecoratorAndManager(object):
  73. def __call__(self, x):
  74. return x
  75. def __enter__(self):
  76. pass
  77. def __exit__(self, exc_type, exc_value, traceback):
  78. pass
  79. class _Optimization(object):
  80. pass
  81. cclass = ccall = cfunc = _EmptyDecoratorAndManager()
  82. returns = wraparound = boundscheck = initializedcheck = nonecheck = \
  83. overflowcheck = embedsignature = cdivision = cdivision_warnings = \
  84. always_allows_keywords = profile = linetrace = infer_types = \
  85. unraisable_tracebacks = freelist = \
  86. lambda _: _EmptyDecoratorAndManager()
  87. exceptval = lambda _=None, check=True: _EmptyDecoratorAndManager()
  88. optimization = _Optimization()
  89. overflowcheck.fold = optimization.use_switch = \
  90. optimization.unpack_method_calls = lambda arg: _EmptyDecoratorAndManager()
  91. final = internal = type_version_tag = no_gc_clear = no_gc = _empty_decorator
  92. _cython_inline = None
  93. def inline(f, *args, **kwds):
  94. if isinstance(f, basestring):
  95. global _cython_inline
  96. if _cython_inline is None:
  97. from Cython.Build.Inline import cython_inline as _cython_inline
  98. return _cython_inline(f, *args, **kwds)
  99. else:
  100. assert len(args) == len(kwds) == 0
  101. return f
  102. def compile(f):
  103. from Cython.Build.Inline import RuntimeCompiledFunction
  104. return RuntimeCompiledFunction(f)
  105. # Special functions
  106. def cdiv(a, b):
  107. q = a / b
  108. if q < 0:
  109. q += 1
  110. return q
  111. def cmod(a, b):
  112. r = a % b
  113. if (a*b) < 0:
  114. r -= b
  115. return r
  116. # Emulated language constructs
  117. def cast(type, *args, **kwargs):
  118. kwargs.pop('typecheck', None)
  119. assert not kwargs
  120. if hasattr(type, '__call__'):
  121. return type(*args)
  122. else:
  123. return args[0]
  124. def sizeof(arg):
  125. return 1
  126. def typeof(arg):
  127. return arg.__class__.__name__
  128. # return type(arg)
  129. def address(arg):
  130. return pointer(type(arg))([arg])
  131. def declare(type=None, value=_Unspecified, **kwds):
  132. if type not in (None, object) and hasattr(type, '__call__'):
  133. if value is not _Unspecified:
  134. return type(value)
  135. else:
  136. return type()
  137. else:
  138. return value
  139. class _nogil(object):
  140. """Support for 'with nogil' statement
  141. """
  142. def __enter__(self):
  143. pass
  144. def __exit__(self, exc_class, exc, tb):
  145. return exc_class is None
  146. nogil = _nogil()
  147. gil = _nogil()
  148. del _nogil
  149. # Emulated types
  150. class CythonMetaType(type):
  151. def __getitem__(type, ix):
  152. return array(type, ix)
  153. CythonTypeObject = CythonMetaType('CythonTypeObject', (object,), {})
  154. class CythonType(CythonTypeObject):
  155. def _pointer(self, n=1):
  156. for i in range(n):
  157. self = pointer(self)
  158. return self
  159. class PointerType(CythonType):
  160. def __init__(self, value=None):
  161. if isinstance(value, (ArrayType, PointerType)):
  162. self._items = [cast(self._basetype, a) for a in value._items]
  163. elif isinstance(value, list):
  164. self._items = [cast(self._basetype, a) for a in value]
  165. elif value is None or value == 0:
  166. self._items = []
  167. else:
  168. raise ValueError
  169. def __getitem__(self, ix):
  170. if ix < 0:
  171. raise IndexError("negative indexing not allowed in C")
  172. return self._items[ix]
  173. def __setitem__(self, ix, value):
  174. if ix < 0:
  175. raise IndexError("negative indexing not allowed in C")
  176. self._items[ix] = cast(self._basetype, value)
  177. def __eq__(self, value):
  178. if value is None and not self._items:
  179. return True
  180. elif type(self) != type(value):
  181. return False
  182. else:
  183. return not self._items and not value._items
  184. def __repr__(self):
  185. return "%s *" % (self._basetype,)
  186. class ArrayType(PointerType):
  187. def __init__(self):
  188. self._items = [None] * self._n
  189. class StructType(CythonType):
  190. def __init__(self, cast_from=_Unspecified, **data):
  191. if cast_from is not _Unspecified:
  192. # do cast
  193. if len(data) > 0:
  194. raise ValueError('Cannot accept keyword arguments when casting.')
  195. if type(cast_from) is not type(self):
  196. raise ValueError('Cannot cast from %s'%cast_from)
  197. for key, value in cast_from.__dict__.items():
  198. setattr(self, key, value)
  199. else:
  200. for key, value in data.items():
  201. setattr(self, key, value)
  202. def __setattr__(self, key, value):
  203. if key in self._members:
  204. self.__dict__[key] = cast(self._members[key], value)
  205. else:
  206. raise AttributeError("Struct has no member '%s'" % key)
  207. class UnionType(CythonType):
  208. def __init__(self, cast_from=_Unspecified, **data):
  209. if cast_from is not _Unspecified:
  210. # do type cast
  211. if len(data) > 0:
  212. raise ValueError('Cannot accept keyword arguments when casting.')
  213. if isinstance(cast_from, dict):
  214. datadict = cast_from
  215. elif type(cast_from) is type(self):
  216. datadict = cast_from.__dict__
  217. else:
  218. raise ValueError('Cannot cast from %s'%cast_from)
  219. else:
  220. datadict = data
  221. if len(datadict) > 1:
  222. raise AttributeError("Union can only store one field at a time.")
  223. for key, value in datadict.items():
  224. setattr(self, key, value)
  225. def __setattr__(self, key, value):
  226. if key in '__dict__':
  227. CythonType.__setattr__(self, key, value)
  228. elif key in self._members:
  229. self.__dict__ = {key: cast(self._members[key], value)}
  230. else:
  231. raise AttributeError("Union has no member '%s'" % key)
  232. def pointer(basetype):
  233. class PointerInstance(PointerType):
  234. _basetype = basetype
  235. return PointerInstance
  236. def array(basetype, n):
  237. class ArrayInstance(ArrayType):
  238. _basetype = basetype
  239. _n = n
  240. return ArrayInstance
  241. def struct(**members):
  242. class StructInstance(StructType):
  243. _members = members
  244. for key in members:
  245. setattr(StructInstance, key, None)
  246. return StructInstance
  247. def union(**members):
  248. class UnionInstance(UnionType):
  249. _members = members
  250. for key in members:
  251. setattr(UnionInstance, key, None)
  252. return UnionInstance
  253. class typedef(CythonType):
  254. def __init__(self, type, name=None):
  255. self._basetype = type
  256. self.name = name
  257. def __call__(self, *arg):
  258. value = cast(self._basetype, *arg)
  259. return value
  260. def __repr__(self):
  261. return self.name or str(self._basetype)
  262. __getitem__ = index_type
  263. class _FusedType(CythonType):
  264. pass
  265. def fused_type(*args):
  266. if not args:
  267. raise TypeError("Expected at least one type as argument")
  268. # Find the numeric type with biggest rank if all types are numeric
  269. rank = -1
  270. for type in args:
  271. if type not in (py_int, py_long, py_float, py_complex):
  272. break
  273. if type_ordering.index(type) > rank:
  274. result_type = type
  275. else:
  276. return result_type
  277. # Not a simple numeric type, return a fused type instance. The result
  278. # isn't really meant to be used, as we can't keep track of the context in
  279. # pure-mode. Casting won't do anything in this case.
  280. return _FusedType()
  281. def _specialized_from_args(signatures, args, kwargs):
  282. "Perhaps this should be implemented in a TreeFragment in Cython code"
  283. raise Exception("yet to be implemented")
  284. py_int = typedef(int, "int")
  285. try:
  286. py_long = typedef(long, "long")
  287. except NameError: # Py3
  288. py_long = typedef(int, "long")
  289. py_float = typedef(float, "float")
  290. py_complex = typedef(complex, "double complex")
  291. # Predefined types
  292. int_types = ['char', 'short', 'Py_UNICODE', 'int', 'Py_UCS4', 'long', 'longlong', 'Py_ssize_t', 'size_t']
  293. float_types = ['longdouble', 'double', 'float']
  294. complex_types = ['longdoublecomplex', 'doublecomplex', 'floatcomplex', 'complex']
  295. other_types = ['bint', 'void', 'Py_tss_t']
  296. to_repr = {
  297. 'longlong': 'long long',
  298. 'longdouble': 'long double',
  299. 'longdoublecomplex': 'long double complex',
  300. 'doublecomplex': 'double complex',
  301. 'floatcomplex': 'float complex',
  302. }.get
  303. gs = globals()
  304. # note: cannot simply name the unicode type here as 2to3 gets in the way and replaces it by str
  305. try:
  306. import __builtin__ as builtins
  307. except ImportError: # Py3
  308. import builtins
  309. gs['unicode'] = typedef(getattr(builtins, 'unicode', str), 'unicode')
  310. del builtins
  311. for name in int_types:
  312. reprname = to_repr(name, name)
  313. gs[name] = typedef(py_int, reprname)
  314. if name not in ('Py_UNICODE', 'Py_UCS4') and not name.endswith('size_t'):
  315. gs['u'+name] = typedef(py_int, "unsigned " + reprname)
  316. gs['s'+name] = typedef(py_int, "signed " + reprname)
  317. for name in float_types:
  318. gs[name] = typedef(py_float, to_repr(name, name))
  319. for name in complex_types:
  320. gs[name] = typedef(py_complex, to_repr(name, name))
  321. bint = typedef(bool, "bint")
  322. void = typedef(None, "void")
  323. Py_tss_t = typedef(None, "Py_tss_t")
  324. for t in int_types + float_types + complex_types + other_types:
  325. for i in range(1, 4):
  326. gs["%s_%s" % ('p'*i, t)] = gs[t]._pointer(i)
  327. NULL = gs['p_void'](0)
  328. # looks like 'gs' has some users out there by now...
  329. #del gs
  330. integral = floating = numeric = _FusedType()
  331. type_ordering = [py_int, py_long, py_float, py_complex]
  332. class CythonDotParallel(object):
  333. """
  334. The cython.parallel module.
  335. """
  336. __all__ = ['parallel', 'prange', 'threadid']
  337. def parallel(self, num_threads=None):
  338. return nogil
  339. def prange(self, start=0, stop=None, step=1, schedule=None, nogil=False):
  340. if stop is None:
  341. stop = start
  342. start = 0
  343. return range(start, stop, step)
  344. def threadid(self):
  345. return 0
  346. # def threadsavailable(self):
  347. # return 1
  348. import sys
  349. sys.modules['cython.parallel'] = CythonDotParallel()
  350. del sys