You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

472 lines
13 KiB

4 years ago
  1. # cython.* namespace for pure mode.
  2. from __future__ import absolute_import
  3. __version__ = "0.29.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. 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. overflowcheck = lambda _: _EmptyDecoratorAndManager()
  89. optimization = _Optimization()
  90. overflowcheck.fold = optimization.use_switch = \
  91. optimization.unpack_method_calls = lambda arg: _EmptyDecoratorAndManager()
  92. final = internal = type_version_tag = no_gc_clear = no_gc = _empty_decorator
  93. _cython_inline = None
  94. def inline(f, *args, **kwds):
  95. if isinstance(f, basestring):
  96. global _cython_inline
  97. if _cython_inline is None:
  98. from Cython.Build.Inline import cython_inline as _cython_inline
  99. return _cython_inline(f, *args, **kwds)
  100. else:
  101. assert len(args) == len(kwds) == 0
  102. return f
  103. def compile(f):
  104. from Cython.Build.Inline import RuntimeCompiledFunction
  105. return RuntimeCompiledFunction(f)
  106. # Special functions
  107. def cdiv(a, b):
  108. q = a / b
  109. if q < 0:
  110. q += 1
  111. return q
  112. def cmod(a, b):
  113. r = a % b
  114. if (a*b) < 0:
  115. r -= b
  116. return r
  117. # Emulated language constructs
  118. def cast(type, *args, **kwargs):
  119. kwargs.pop('typecheck', None)
  120. assert not kwargs
  121. if hasattr(type, '__call__'):
  122. return type(*args)
  123. else:
  124. return args[0]
  125. def sizeof(arg):
  126. return 1
  127. def typeof(arg):
  128. return arg.__class__.__name__
  129. # return type(arg)
  130. def address(arg):
  131. return pointer(type(arg))([arg])
  132. def declare(type=None, value=_Unspecified, **kwds):
  133. if type not in (None, object) and hasattr(type, '__call__'):
  134. if value is not _Unspecified:
  135. return type(value)
  136. else:
  137. return type()
  138. else:
  139. return value
  140. class _nogil(object):
  141. """Support for 'with nogil' statement and @nogil decorator.
  142. """
  143. def __call__(self, x):
  144. if callable(x):
  145. # Used as function decorator => return the function unchanged.
  146. return x
  147. # Used as conditional context manager or to create an "@nogil(True/False)" decorator => keep going.
  148. return self
  149. def __enter__(self):
  150. pass
  151. def __exit__(self, exc_class, exc, tb):
  152. return exc_class is None
  153. nogil = _nogil()
  154. gil = _nogil()
  155. del _nogil
  156. # Emulated types
  157. class CythonMetaType(type):
  158. def __getitem__(type, ix):
  159. return array(type, ix)
  160. CythonTypeObject = CythonMetaType('CythonTypeObject', (object,), {})
  161. class CythonType(CythonTypeObject):
  162. def _pointer(self, n=1):
  163. for i in range(n):
  164. self = pointer(self)
  165. return self
  166. class PointerType(CythonType):
  167. def __init__(self, value=None):
  168. if isinstance(value, (ArrayType, PointerType)):
  169. self._items = [cast(self._basetype, a) for a in value._items]
  170. elif isinstance(value, list):
  171. self._items = [cast(self._basetype, a) for a in value]
  172. elif value is None or value == 0:
  173. self._items = []
  174. else:
  175. raise ValueError
  176. def __getitem__(self, ix):
  177. if ix < 0:
  178. raise IndexError("negative indexing not allowed in C")
  179. return self._items[ix]
  180. def __setitem__(self, ix, value):
  181. if ix < 0:
  182. raise IndexError("negative indexing not allowed in C")
  183. self._items[ix] = cast(self._basetype, value)
  184. def __eq__(self, value):
  185. if value is None and not self._items:
  186. return True
  187. elif type(self) != type(value):
  188. return False
  189. else:
  190. return not self._items and not value._items
  191. def __repr__(self):
  192. return "%s *" % (self._basetype,)
  193. class ArrayType(PointerType):
  194. def __init__(self):
  195. self._items = [None] * self._n
  196. class StructType(CythonType):
  197. def __init__(self, cast_from=_Unspecified, **data):
  198. if cast_from is not _Unspecified:
  199. # do cast
  200. if len(data) > 0:
  201. raise ValueError('Cannot accept keyword arguments when casting.')
  202. if type(cast_from) is not type(self):
  203. raise ValueError('Cannot cast from %s'%cast_from)
  204. for key, value in cast_from.__dict__.items():
  205. setattr(self, key, value)
  206. else:
  207. for key, value in data.items():
  208. setattr(self, key, value)
  209. def __setattr__(self, key, value):
  210. if key in self._members:
  211. self.__dict__[key] = cast(self._members[key], value)
  212. else:
  213. raise AttributeError("Struct has no member '%s'" % key)
  214. class UnionType(CythonType):
  215. def __init__(self, cast_from=_Unspecified, **data):
  216. if cast_from is not _Unspecified:
  217. # do type cast
  218. if len(data) > 0:
  219. raise ValueError('Cannot accept keyword arguments when casting.')
  220. if isinstance(cast_from, dict):
  221. datadict = cast_from
  222. elif type(cast_from) is type(self):
  223. datadict = cast_from.__dict__
  224. else:
  225. raise ValueError('Cannot cast from %s'%cast_from)
  226. else:
  227. datadict = data
  228. if len(datadict) > 1:
  229. raise AttributeError("Union can only store one field at a time.")
  230. for key, value in datadict.items():
  231. setattr(self, key, value)
  232. def __setattr__(self, key, value):
  233. if key in '__dict__':
  234. CythonType.__setattr__(self, key, value)
  235. elif key in self._members:
  236. self.__dict__ = {key: cast(self._members[key], value)}
  237. else:
  238. raise AttributeError("Union has no member '%s'" % key)
  239. def pointer(basetype):
  240. class PointerInstance(PointerType):
  241. _basetype = basetype
  242. return PointerInstance
  243. def array(basetype, n):
  244. class ArrayInstance(ArrayType):
  245. _basetype = basetype
  246. _n = n
  247. return ArrayInstance
  248. def struct(**members):
  249. class StructInstance(StructType):
  250. _members = members
  251. for key in members:
  252. setattr(StructInstance, key, None)
  253. return StructInstance
  254. def union(**members):
  255. class UnionInstance(UnionType):
  256. _members = members
  257. for key in members:
  258. setattr(UnionInstance, key, None)
  259. return UnionInstance
  260. class typedef(CythonType):
  261. def __init__(self, type, name=None):
  262. self._basetype = type
  263. self.name = name
  264. def __call__(self, *arg):
  265. value = cast(self._basetype, *arg)
  266. return value
  267. def __repr__(self):
  268. return self.name or str(self._basetype)
  269. __getitem__ = index_type
  270. class _FusedType(CythonType):
  271. pass
  272. def fused_type(*args):
  273. if not args:
  274. raise TypeError("Expected at least one type as argument")
  275. # Find the numeric type with biggest rank if all types are numeric
  276. rank = -1
  277. for type in args:
  278. if type not in (py_int, py_long, py_float, py_complex):
  279. break
  280. if type_ordering.index(type) > rank:
  281. result_type = type
  282. else:
  283. return result_type
  284. # Not a simple numeric type, return a fused type instance. The result
  285. # isn't really meant to be used, as we can't keep track of the context in
  286. # pure-mode. Casting won't do anything in this case.
  287. return _FusedType()
  288. def _specialized_from_args(signatures, args, kwargs):
  289. "Perhaps this should be implemented in a TreeFragment in Cython code"
  290. raise Exception("yet to be implemented")
  291. py_int = typedef(int, "int")
  292. try:
  293. py_long = typedef(long, "long")
  294. except NameError: # Py3
  295. py_long = typedef(int, "long")
  296. py_float = typedef(float, "float")
  297. py_complex = typedef(complex, "double complex")
  298. # Predefined types
  299. int_types = ['char', 'short', 'Py_UNICODE', 'int', 'Py_UCS4', 'long', 'longlong', 'Py_ssize_t', 'size_t']
  300. float_types = ['longdouble', 'double', 'float']
  301. complex_types = ['longdoublecomplex', 'doublecomplex', 'floatcomplex', 'complex']
  302. other_types = ['bint', 'void', 'Py_tss_t']
  303. to_repr = {
  304. 'longlong': 'long long',
  305. 'longdouble': 'long double',
  306. 'longdoublecomplex': 'long double complex',
  307. 'doublecomplex': 'double complex',
  308. 'floatcomplex': 'float complex',
  309. }.get
  310. gs = globals()
  311. # note: cannot simply name the unicode type here as 2to3 gets in the way and replaces it by str
  312. try:
  313. import __builtin__ as builtins
  314. except ImportError: # Py3
  315. import builtins
  316. gs['unicode'] = typedef(getattr(builtins, 'unicode', str), 'unicode')
  317. del builtins
  318. for name in int_types:
  319. reprname = to_repr(name, name)
  320. gs[name] = typedef(py_int, reprname)
  321. if name not in ('Py_UNICODE', 'Py_UCS4') and not name.endswith('size_t'):
  322. gs['u'+name] = typedef(py_int, "unsigned " + reprname)
  323. gs['s'+name] = typedef(py_int, "signed " + reprname)
  324. for name in float_types:
  325. gs[name] = typedef(py_float, to_repr(name, name))
  326. for name in complex_types:
  327. gs[name] = typedef(py_complex, to_repr(name, name))
  328. bint = typedef(bool, "bint")
  329. void = typedef(None, "void")
  330. Py_tss_t = typedef(None, "Py_tss_t")
  331. for t in int_types + float_types + complex_types + other_types:
  332. for i in range(1, 4):
  333. gs["%s_%s" % ('p'*i, t)] = gs[t]._pointer(i)
  334. NULL = gs['p_void'](0)
  335. # looks like 'gs' has some users out there by now...
  336. #del gs
  337. integral = floating = numeric = _FusedType()
  338. type_ordering = [py_int, py_long, py_float, py_complex]
  339. class CythonDotParallel(object):
  340. """
  341. The cython.parallel module.
  342. """
  343. __all__ = ['parallel', 'prange', 'threadid']
  344. def parallel(self, num_threads=None):
  345. return nogil
  346. def prange(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None):
  347. if stop is None:
  348. stop = start
  349. start = 0
  350. return range(start, stop, step)
  351. def threadid(self):
  352. return 0
  353. # def threadsavailable(self):
  354. # return 1
  355. import sys
  356. sys.modules['cython.parallel'] = CythonDotParallel()
  357. del sys