Cython 3.2.0__cp39-abi3-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +350 -0
  4. Cython/Build/Dependencies.py +1314 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +463 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/SharedModule.py +94 -0
  9. Cython/Build/Tests/TestCyCache.py +194 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +815 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +680 -0
  23. Cython/Compiler/Builtin.py +984 -0
  24. Cython/Compiler/CmdLine.py +263 -0
  25. Cython/Compiler/Code.pxd +149 -0
  26. Cython/Compiler/Code.py +3746 -0
  27. Cython/Compiler/Code.pyd +0 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +191 -0
  30. Cython/Compiler/Dataclass.py +864 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +297 -0
  33. Cython/Compiler/ExprNodes.py +15562 -0
  34. Cython/Compiler/FlowControl.pxd +97 -0
  35. Cython/Compiler/FlowControl.py +1451 -0
  36. Cython/Compiler/FlowControl.pyd +0 -0
  37. Cython/Compiler/FusedNode.py +971 -0
  38. Cython/Compiler/FusedNode.pyd +0 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +421 -0
  42. Cython/Compiler/LineTable.py +114 -0
  43. Cython/Compiler/LineTable.pyd +0 -0
  44. Cython/Compiler/Main.py +857 -0
  45. Cython/Compiler/MatchCaseNodes.py +259 -0
  46. Cython/Compiler/MemoryView.py +905 -0
  47. Cython/Compiler/ModuleNode.py +4235 -0
  48. Cython/Compiler/Naming.py +363 -0
  49. Cython/Compiler/Nodes.py +10831 -0
  50. Cython/Compiler/Optimize.py +5288 -0
  51. Cython/Compiler/Options.py +843 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +78 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4638 -0
  54. Cython/Compiler/Parsing.pxd +9 -0
  55. Cython/Compiler/Parsing.py +4775 -0
  56. Cython/Compiler/Parsing.pyd +0 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +5870 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.pxd +48 -0
  61. Cython/Compiler/Scanning.py +701 -0
  62. Cython/Compiler/Scanning.pyd +0 -0
  63. Cython/Compiler/StringEncoding.py +298 -0
  64. Cython/Compiler/Symtab.py +3073 -0
  65. Cython/Compiler/Tests/TestBuffer.py +105 -0
  66. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  67. Cython/Compiler/Tests/TestCmdLine.py +586 -0
  68. Cython/Compiler/Tests/TestCode.py +144 -0
  69. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  70. Cython/Compiler/Tests/TestGrammar.py +202 -0
  71. Cython/Compiler/Tests/TestMemView.py +71 -0
  72. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  73. Cython/Compiler/Tests/TestScanning.py +134 -0
  74. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  75. Cython/Compiler/Tests/TestStringEncoding.py +21 -0
  76. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  77. Cython/Compiler/Tests/TestTreePath.py +103 -0
  78. Cython/Compiler/Tests/TestTypes.py +75 -0
  79. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  80. Cython/Compiler/Tests/TestVisitor.py +61 -0
  81. Cython/Compiler/Tests/Utils.py +36 -0
  82. Cython/Compiler/Tests/__init__.py +1 -0
  83. Cython/Compiler/TreeFragment.py +278 -0
  84. Cython/Compiler/TreePath.py +303 -0
  85. Cython/Compiler/TypeInference.py +591 -0
  86. Cython/Compiler/TypeSlots.py +1174 -0
  87. Cython/Compiler/UFuncs.py +311 -0
  88. Cython/Compiler/UtilNodes.py +389 -0
  89. Cython/Compiler/UtilityCode.py +344 -0
  90. Cython/Compiler/Version.py +8 -0
  91. Cython/Compiler/Visitor.pxd +53 -0
  92. Cython/Compiler/Visitor.py +861 -0
  93. Cython/Compiler/Visitor.pyd +0 -0
  94. Cython/Compiler/__init__.py +1 -0
  95. Cython/Coverage.py +448 -0
  96. Cython/Debugger/Cygdb.py +177 -0
  97. Cython/Debugger/DebugWriter.py +82 -0
  98. Cython/Debugger/Tests/TestLibCython.py +275 -0
  99. Cython/Debugger/Tests/__init__.py +1 -0
  100. Cython/Debugger/Tests/cfuncs.c +8 -0
  101. Cython/Debugger/Tests/codefile +49 -0
  102. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  103. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  104. Cython/Debugger/__init__.py +1 -0
  105. Cython/Debugger/libcython.py +1548 -0
  106. Cython/Debugger/libpython.py +2821 -0
  107. Cython/Debugging.py +20 -0
  108. Cython/Distutils/__init__.py +2 -0
  109. Cython/Distutils/build_ext.py +139 -0
  110. Cython/Distutils/extension.py +96 -0
  111. Cython/Distutils/old_build_ext.py +351 -0
  112. Cython/Includes/cpython/__init__.pxd +173 -0
  113. Cython/Includes/cpython/array.pxd +178 -0
  114. Cython/Includes/cpython/bool.pxd +37 -0
  115. Cython/Includes/cpython/buffer.pxd +112 -0
  116. Cython/Includes/cpython/bytearray.pxd +33 -0
  117. Cython/Includes/cpython/bytes.pxd +200 -0
  118. Cython/Includes/cpython/cellobject.pxd +35 -0
  119. Cython/Includes/cpython/ceval.pxd +8 -0
  120. Cython/Includes/cpython/codecs.pxd +121 -0
  121. Cython/Includes/cpython/complex.pxd +60 -0
  122. Cython/Includes/cpython/contextvars.pxd +145 -0
  123. Cython/Includes/cpython/conversion.pxd +36 -0
  124. Cython/Includes/cpython/datetime.pxd +395 -0
  125. Cython/Includes/cpython/descr.pxd +26 -0
  126. Cython/Includes/cpython/dict.pxd +187 -0
  127. Cython/Includes/cpython/exc.pxd +263 -0
  128. Cython/Includes/cpython/fileobject.pxd +57 -0
  129. Cython/Includes/cpython/float.pxd +47 -0
  130. Cython/Includes/cpython/function.pxd +65 -0
  131. Cython/Includes/cpython/genobject.pxd +25 -0
  132. Cython/Includes/cpython/getargs.pxd +12 -0
  133. Cython/Includes/cpython/instance.pxd +25 -0
  134. Cython/Includes/cpython/iterator.pxd +36 -0
  135. Cython/Includes/cpython/iterobject.pxd +24 -0
  136. Cython/Includes/cpython/list.pxd +92 -0
  137. Cython/Includes/cpython/long.pxd +149 -0
  138. Cython/Includes/cpython/longintrepr.pxd +14 -0
  139. Cython/Includes/cpython/mapping.pxd +63 -0
  140. Cython/Includes/cpython/marshal.pxd +66 -0
  141. Cython/Includes/cpython/mem.pxd +120 -0
  142. Cython/Includes/cpython/memoryview.pxd +50 -0
  143. Cython/Includes/cpython/method.pxd +49 -0
  144. Cython/Includes/cpython/module.pxd +208 -0
  145. Cython/Includes/cpython/number.pxd +258 -0
  146. Cython/Includes/cpython/object.pxd +433 -0
  147. Cython/Includes/cpython/pycapsule.pxd +143 -0
  148. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  149. Cython/Includes/cpython/pyport.pxd +8 -0
  150. Cython/Includes/cpython/pystate.pxd +95 -0
  151. Cython/Includes/cpython/pythread.pxd +53 -0
  152. Cython/Includes/cpython/ref.pxd +141 -0
  153. Cython/Includes/cpython/sequence.pxd +134 -0
  154. Cython/Includes/cpython/set.pxd +119 -0
  155. Cython/Includes/cpython/slice.pxd +70 -0
  156. Cython/Includes/cpython/time.pxd +129 -0
  157. Cython/Includes/cpython/tuple.pxd +72 -0
  158. Cython/Includes/cpython/type.pxd +53 -0
  159. Cython/Includes/cpython/unicode.pxd +639 -0
  160. Cython/Includes/cpython/version.pxd +32 -0
  161. Cython/Includes/cpython/weakref.pxd +78 -0
  162. Cython/Includes/libc/__init__.pxd +1 -0
  163. Cython/Includes/libc/complex.pxd +35 -0
  164. Cython/Includes/libc/errno.pxd +127 -0
  165. Cython/Includes/libc/float.pxd +43 -0
  166. Cython/Includes/libc/limits.pxd +28 -0
  167. Cython/Includes/libc/locale.pxd +46 -0
  168. Cython/Includes/libc/math.pxd +209 -0
  169. Cython/Includes/libc/setjmp.pxd +10 -0
  170. Cython/Includes/libc/signal.pxd +64 -0
  171. Cython/Includes/libc/stddef.pxd +9 -0
  172. Cython/Includes/libc/stdint.pxd +105 -0
  173. Cython/Includes/libc/stdio.pxd +80 -0
  174. Cython/Includes/libc/stdlib.pxd +72 -0
  175. Cython/Includes/libc/string.pxd +50 -0
  176. Cython/Includes/libc/threads.pxd +234 -0
  177. Cython/Includes/libc/time.pxd +52 -0
  178. Cython/Includes/libcpp/__init__.pxd +4 -0
  179. Cython/Includes/libcpp/algorithm.pxd +320 -0
  180. Cython/Includes/libcpp/any.pxd +16 -0
  181. Cython/Includes/libcpp/atomic.pxd +59 -0
  182. Cython/Includes/libcpp/barrier.pxd +22 -0
  183. Cython/Includes/libcpp/bit.pxd +29 -0
  184. Cython/Includes/libcpp/cast.pxd +12 -0
  185. Cython/Includes/libcpp/cmath.pxd +518 -0
  186. Cython/Includes/libcpp/complex.pxd +106 -0
  187. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  188. Cython/Includes/libcpp/deque.pxd +165 -0
  189. Cython/Includes/libcpp/exception.pxd +86 -0
  190. Cython/Includes/libcpp/execution.pxd +15 -0
  191. Cython/Includes/libcpp/forward_list.pxd +63 -0
  192. Cython/Includes/libcpp/functional.pxd +26 -0
  193. Cython/Includes/libcpp/future.pxd +103 -0
  194. Cython/Includes/libcpp/iterator.pxd +34 -0
  195. Cython/Includes/libcpp/latch.pxd +17 -0
  196. Cython/Includes/libcpp/limits.pxd +61 -0
  197. Cython/Includes/libcpp/list.pxd +117 -0
  198. Cython/Includes/libcpp/map.pxd +252 -0
  199. Cython/Includes/libcpp/memory.pxd +115 -0
  200. Cython/Includes/libcpp/mutex.pxd +387 -0
  201. Cython/Includes/libcpp/numbers.pxd +15 -0
  202. Cython/Includes/libcpp/numeric.pxd +131 -0
  203. Cython/Includes/libcpp/optional.pxd +34 -0
  204. Cython/Includes/libcpp/pair.pxd +1 -0
  205. Cython/Includes/libcpp/queue.pxd +25 -0
  206. Cython/Includes/libcpp/random.pxd +166 -0
  207. Cython/Includes/libcpp/semaphore.pxd +43 -0
  208. Cython/Includes/libcpp/set.pxd +228 -0
  209. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  210. Cython/Includes/libcpp/span.pxd +87 -0
  211. Cython/Includes/libcpp/stack.pxd +11 -0
  212. Cython/Includes/libcpp/stop_token.pxd +117 -0
  213. Cython/Includes/libcpp/string.pxd +355 -0
  214. Cython/Includes/libcpp/string_view.pxd +183 -0
  215. Cython/Includes/libcpp/typeindex.pxd +15 -0
  216. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  217. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  218. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  219. Cython/Includes/libcpp/utility.pxd +30 -0
  220. Cython/Includes/libcpp/vector.pxd +186 -0
  221. Cython/Includes/numpy/math.pxd +150 -0
  222. Cython/Includes/openmp.pxd +50 -0
  223. Cython/Includes/posix/__init__.pxd +1 -0
  224. Cython/Includes/posix/dlfcn.pxd +14 -0
  225. Cython/Includes/posix/fcntl.pxd +86 -0
  226. Cython/Includes/posix/ioctl.pxd +4 -0
  227. Cython/Includes/posix/mman.pxd +101 -0
  228. Cython/Includes/posix/resource.pxd +57 -0
  229. Cython/Includes/posix/select.pxd +21 -0
  230. Cython/Includes/posix/signal.pxd +73 -0
  231. Cython/Includes/posix/stat.pxd +98 -0
  232. Cython/Includes/posix/stdio.pxd +37 -0
  233. Cython/Includes/posix/stdlib.pxd +29 -0
  234. Cython/Includes/posix/strings.pxd +9 -0
  235. Cython/Includes/posix/time.pxd +71 -0
  236. Cython/Includes/posix/types.pxd +30 -0
  237. Cython/Includes/posix/uio.pxd +26 -0
  238. Cython/Includes/posix/unistd.pxd +271 -0
  239. Cython/Includes/posix/wait.pxd +38 -0
  240. Cython/Plex/Actions.pxd +24 -0
  241. Cython/Plex/Actions.py +119 -0
  242. Cython/Plex/Actions.pyd +0 -0
  243. Cython/Plex/DFA.pxd +14 -0
  244. Cython/Plex/DFA.py +164 -0
  245. Cython/Plex/DFA.pyd +0 -0
  246. Cython/Plex/Errors.py +48 -0
  247. Cython/Plex/Lexicons.py +178 -0
  248. Cython/Plex/Machines.pxd +36 -0
  249. Cython/Plex/Machines.py +238 -0
  250. Cython/Plex/Machines.pyd +0 -0
  251. Cython/Plex/Regexps.py +535 -0
  252. Cython/Plex/Scanners.pxd +45 -0
  253. Cython/Plex/Scanners.py +328 -0
  254. Cython/Plex/Scanners.pyd +0 -0
  255. Cython/Plex/Transitions.pxd +14 -0
  256. Cython/Plex/Transitions.py +239 -0
  257. Cython/Plex/Transitions.pyd +0 -0
  258. Cython/Plex/__init__.py +34 -0
  259. Cython/Runtime/__init__.py +1 -0
  260. Cython/Runtime/refnanny.pyd +0 -0
  261. Cython/Runtime/refnanny.pyx +237 -0
  262. Cython/Shadow.py +690 -0
  263. Cython/Shadow.pyi +521 -0
  264. Cython/StringIOTree.py +170 -0
  265. Cython/StringIOTree.pyd +0 -0
  266. Cython/Tempita/__init__.py +4 -0
  267. Cython/Tempita/_looper.py +154 -0
  268. Cython/Tempita/_tempita.py +1091 -0
  269. Cython/Tempita/_tempita.pyd +0 -0
  270. Cython/TestUtils.py +422 -0
  271. Cython/Tests/TestCodeWriter.py +128 -0
  272. Cython/Tests/TestCythonUtils.py +202 -0
  273. Cython/Tests/TestJediTyper.py +223 -0
  274. Cython/Tests/TestShadow.py +114 -0
  275. Cython/Tests/TestStringIOTree.py +67 -0
  276. Cython/Tests/TestTestUtils.py +90 -0
  277. Cython/Tests/__init__.py +1 -0
  278. Cython/Tests/xmlrunner.py +390 -0
  279. Cython/Utility/AsyncGen.c +1031 -0
  280. Cython/Utility/Buffer.c +865 -0
  281. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  282. Cython/Utility/Builtins.c +810 -0
  283. Cython/Utility/CConvert.pyx +134 -0
  284. Cython/Utility/CMath.c +104 -0
  285. Cython/Utility/CommonStructures.c +226 -0
  286. Cython/Utility/Complex.c +378 -0
  287. Cython/Utility/Coroutine.c +2300 -0
  288. Cython/Utility/CpdefEnums.pyx +103 -0
  289. Cython/Utility/CppConvert.pyx +282 -0
  290. Cython/Utility/CppSupport.cpp +151 -0
  291. Cython/Utility/CythonFunction.c +1832 -0
  292. Cython/Utility/Dataclasses.c +101 -0
  293. Cython/Utility/Embed.c +121 -0
  294. Cython/Utility/Exceptions.c +1016 -0
  295. Cython/Utility/ExtensionTypes.c +996 -0
  296. Cython/Utility/FunctionArguments.c +1043 -0
  297. Cython/Utility/FusedFunction.pyx +44 -0
  298. Cython/Utility/ImportExport.c +907 -0
  299. Cython/Utility/MemoryView.pxd +188 -0
  300. Cython/Utility/MemoryView.pyx +1482 -0
  301. Cython/Utility/MemoryView_C.c +927 -0
  302. Cython/Utility/ModuleSetupCode.c +3203 -0
  303. Cython/Utility/NumpyImportArray.c +46 -0
  304. Cython/Utility/ObjectHandling.c +3273 -0
  305. Cython/Utility/Optimize.c +1603 -0
  306. Cython/Utility/Overflow.c +384 -0
  307. Cython/Utility/Printing.c +86 -0
  308. Cython/Utility/Profile.c +732 -0
  309. Cython/Utility/StringTools.c +1379 -0
  310. Cython/Utility/Synchronization.c +399 -0
  311. Cython/Utility/TString.c +356 -0
  312. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  313. Cython/Utility/TestCythonScope.pyx +75 -0
  314. Cython/Utility/TestUtilityLoader.c +12 -0
  315. Cython/Utility/TypeConversion.c +1385 -0
  316. Cython/Utility/UFuncs.pyx +50 -0
  317. Cython/Utility/UFuncs_C.c +89 -0
  318. Cython/Utility/__init__.py +28 -0
  319. Cython/Utility/arrayarray.h +167 -0
  320. Cython/Utils.py +687 -0
  321. Cython/Utils.pyd +0 -0
  322. Cython/__init__.py +10 -0
  323. Cython/__init__.pyi +7 -0
  324. Cython/py.typed +0 -0
  325. cython-3.2.0.dist-info/METADATA +85 -0
  326. cython-3.2.0.dist-info/RECORD +333 -0
  327. cython-3.2.0.dist-info/WHEEL +5 -0
  328. cython-3.2.0.dist-info/entry_points.txt +4 -0
  329. cython-3.2.0.dist-info/top_level.txt +3 -0
  330. cython.py +29 -0
  331. pyximport/__init__.py +4 -0
  332. pyximport/pyxbuild.py +160 -0
  333. pyximport/pyximport.py +482 -0
@@ -0,0 +1,680 @@
1
+ from .Visitor import CythonTransform
2
+ from .ModuleNode import ModuleNode
3
+ from .Errors import CompileError
4
+ from .UtilityCode import CythonUtilityCode
5
+ from .Code import UtilityCode, TempitaUtilityCode
6
+
7
+ from . import Options
8
+ from . import Interpreter
9
+ from . import PyrexTypes
10
+ from . import Naming
11
+ from . import Symtab
12
+
13
+ def dedent(text, reindent=0):
14
+ from textwrap import dedent
15
+ text = dedent(text)
16
+ if reindent > 0:
17
+ indent = " " * reindent
18
+ text = '\n'.join([indent + x for x in text.split('\n')])
19
+ return text
20
+
21
+ class IntroduceBufferAuxiliaryVars(CythonTransform):
22
+
23
+ #
24
+ # Entry point
25
+ #
26
+
27
+ buffers_exists = False
28
+ using_memoryview = False
29
+
30
+ def __call__(self, node):
31
+ assert isinstance(node, ModuleNode)
32
+ self.max_ndim = 0
33
+ result = super().__call__(node)
34
+ if self.buffers_exists:
35
+ use_bufstruct_declare_code(node.scope)
36
+
37
+ return result
38
+
39
+
40
+ #
41
+ # Basic operations for transforms
42
+ #
43
+ def handle_scope(self, node, scope):
44
+ # For all buffers, insert extra variables in the scope.
45
+ # The variables are also accessible from the buffer_info
46
+ # on the buffer entry
47
+ scope_items = scope.entries.items()
48
+ bufvars = [entry for name, entry in scope_items if entry.type.is_buffer]
49
+ if len(bufvars) > 0:
50
+ bufvars.sort(key=lambda entry: entry.name)
51
+ self.buffers_exists = True
52
+
53
+ memviewslicevars = [entry for name, entry in scope_items if entry.type.is_memoryviewslice]
54
+ if len(memviewslicevars) > 0:
55
+ self.buffers_exists = True
56
+
57
+
58
+ for (name, entry) in scope_items:
59
+ if name == 'memoryview' and isinstance(entry.utility_code_definition, CythonUtilityCode):
60
+ self.using_memoryview = True
61
+ break
62
+ del scope_items
63
+
64
+ if isinstance(node, ModuleNode) and len(bufvars) > 0:
65
+ # for now...note that pos is wrong
66
+ raise CompileError(node.pos, "Buffer vars not allowed in module scope")
67
+ for entry in bufvars:
68
+ if entry.type.dtype.is_ptr:
69
+ raise CompileError(node.pos, "Buffers with pointer types not yet supported.")
70
+
71
+ name = entry.name
72
+ buftype = entry.type
73
+ if buftype.ndim > Options.buffer_max_dims:
74
+ raise CompileError(node.pos,
75
+ "Buffer ndims exceeds Options.buffer_max_dims = %d" % Options.buffer_max_dims)
76
+ if buftype.ndim > self.max_ndim:
77
+ self.max_ndim = buftype.ndim
78
+
79
+ # Declare auxiliary vars
80
+ def decvar(type, prefix):
81
+ cname = scope.mangle(prefix, name)
82
+ aux_var = scope.declare_var(name=None, cname=cname,
83
+ type=type, pos=node.pos)
84
+ if entry.is_arg:
85
+ aux_var.used = True # otherwise, NameNode will mark whether it is used
86
+
87
+ return aux_var
88
+
89
+ auxvars = ((PyrexTypes.c_pyx_buffer_nd_type, Naming.pybuffernd_prefix),
90
+ (PyrexTypes.c_pyx_buffer_type, Naming.pybufferstruct_prefix))
91
+ pybuffernd, rcbuffer = [decvar(type, prefix) for (type, prefix) in auxvars]
92
+
93
+ entry.buffer_aux = Symtab.BufferAux(pybuffernd, rcbuffer)
94
+
95
+ scope.buffer_entries = bufvars
96
+ self.scope = scope
97
+
98
+ def visit_ModuleNode(self, node):
99
+ self.handle_scope(node, node.scope)
100
+ self.visitchildren(node)
101
+ return node
102
+
103
+ def visit_FuncDefNode(self, node):
104
+ self.handle_scope(node, node.local_scope)
105
+ self.visitchildren(node)
106
+ return node
107
+
108
+ #
109
+ # Analysis
110
+ #
111
+ buffer_options = ("dtype", "ndim", "mode", "negative_indices", "cast") # ordered!
112
+ buffer_defaults = {"ndim": 1, "mode": "full", "negative_indices": True, "cast": False}
113
+ buffer_positional_options_count = 1 # anything beyond this needs keyword argument
114
+
115
+ ERR_BUF_OPTION_UNKNOWN = '"%s" is not a buffer option'
116
+ ERR_BUF_TOO_MANY = 'Too many buffer options'
117
+ ERR_BUF_DUP = '"%s" buffer option already supplied'
118
+ ERR_BUF_MISSING = '"%s" missing'
119
+ ERR_BUF_MODE = 'Only allowed buffer modes are: "c", "fortran", "full", "strided" (as a compile-time string)'
120
+ ERR_BUF_NDIM = 'ndim must be a non-negative integer'
121
+ ERR_BUF_DTYPE = 'dtype must be "object", numeric type or a struct'
122
+ ERR_BUF_BOOL = '"%s" must be a boolean'
123
+
124
+ def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, need_complete=True):
125
+ """
126
+ Must be called during type analysis, as analyse is called
127
+ on the dtype argument.
128
+
129
+ posargs and dictargs should consist of a list and a dict
130
+ of tuples (value, pos). Defaults should be a dict of values.
131
+
132
+ Returns a dict containing all the options a buffer can have and
133
+ its value (with the positions stripped).
134
+ """
135
+ if defaults is None:
136
+ defaults = buffer_defaults
137
+
138
+ posargs, dictargs = Interpreter.interpret_compiletime_options(
139
+ posargs, dictargs, type_env=env, type_args=(0, 'dtype'))
140
+
141
+ if len(posargs) > buffer_positional_options_count:
142
+ raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY)
143
+
144
+ options = {}
145
+ for name, (value, pos) in dictargs.items():
146
+ if name not in buffer_options:
147
+ raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
148
+ options[name] = value
149
+
150
+ for name, (value, pos) in zip(buffer_options, posargs):
151
+ if name not in buffer_options:
152
+ raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
153
+ if name in options:
154
+ raise CompileError(pos, ERR_BUF_DUP % name)
155
+ options[name] = value
156
+
157
+ # Check that they are all there and copy defaults
158
+ for name in buffer_options:
159
+ if name not in options:
160
+ try:
161
+ options[name] = defaults[name]
162
+ except KeyError:
163
+ if need_complete:
164
+ raise CompileError(globalpos, ERR_BUF_MISSING % name)
165
+
166
+ dtype = options.get("dtype")
167
+ if dtype and dtype.is_extension_type:
168
+ raise CompileError(globalpos, ERR_BUF_DTYPE)
169
+
170
+ ndim = options.get("ndim")
171
+ if ndim and (not isinstance(ndim, int) or ndim < 0):
172
+ raise CompileError(globalpos, ERR_BUF_NDIM)
173
+
174
+ mode = options.get("mode")
175
+ if mode and not (mode in ('full', 'strided', 'c', 'fortran')):
176
+ raise CompileError(globalpos, ERR_BUF_MODE)
177
+
178
+ def assert_bool(name):
179
+ x = options.get(name)
180
+ if not isinstance(x, bool):
181
+ raise CompileError(globalpos, ERR_BUF_BOOL % name)
182
+
183
+ assert_bool('negative_indices')
184
+ assert_bool('cast')
185
+
186
+ return options
187
+
188
+
189
+ #
190
+ # Code generation
191
+ #
192
+
193
+ class BufferEntry:
194
+ def __init__(self, entry):
195
+ self.entry = entry
196
+ self.type = entry.type
197
+ self.cname = entry.buffer_aux.buflocal_nd_var.cname
198
+ self.buf_ptr = "%s.rcbuffer->pybuffer.buf" % self.cname
199
+ self.buf_ptr_type = entry.type.buffer_ptr_type
200
+ self.init_attributes()
201
+
202
+ def init_attributes(self):
203
+ self.shape = self.get_buf_shapevars()
204
+ self.strides = self.get_buf_stridevars()
205
+ self.suboffsets = self.get_buf_suboffsetvars()
206
+
207
+ def get_buf_suboffsetvars(self):
208
+ return self._for_all_ndim("%s.diminfo[%d].suboffsets")
209
+
210
+ def get_buf_stridevars(self):
211
+ return self._for_all_ndim("%s.diminfo[%d].strides")
212
+
213
+ def get_buf_shapevars(self):
214
+ return self._for_all_ndim("%s.diminfo[%d].shape")
215
+
216
+ def _for_all_ndim(self, s):
217
+ return [s % (self.cname, i) for i in range(self.type.ndim)]
218
+
219
+ def generate_buffer_lookup_code(self, code, index_cnames):
220
+ # Create buffer lookup and return it
221
+ # This is done via utility macros/inline functions, which vary
222
+ # according to the access mode used.
223
+ params = []
224
+ nd = self.type.ndim
225
+ mode = self.type.mode
226
+ if mode == 'full':
227
+ for i, s, o in zip(index_cnames,
228
+ self.get_buf_stridevars(),
229
+ self.get_buf_suboffsetvars()):
230
+ params.append(i)
231
+ params.append(s)
232
+ params.append(o)
233
+ funcname = "__Pyx_BufPtrFull%dd" % nd
234
+ funcgen = buf_lookup_full_code
235
+ else:
236
+ if mode == 'strided':
237
+ funcname = "__Pyx_BufPtrStrided%dd" % nd
238
+ funcgen = buf_lookup_strided_code
239
+ elif mode == 'c':
240
+ funcname = "__Pyx_BufPtrCContig%dd" % nd
241
+ funcgen = buf_lookup_c_code
242
+ elif mode == 'fortran':
243
+ funcname = "__Pyx_BufPtrFortranContig%dd" % nd
244
+ funcgen = buf_lookup_fortran_code
245
+ else:
246
+ assert False
247
+ for i, s in zip(index_cnames, self.get_buf_stridevars()):
248
+ params.append(i)
249
+ params.append(s)
250
+
251
+ # Make sure the utility code is available
252
+ if funcname not in code.globalstate.utility_codes:
253
+ code.globalstate.utility_codes.add(funcname)
254
+ protocode = code.globalstate['utility_code_proto']
255
+ defcode = code.globalstate['utility_code_def']
256
+ funcgen(protocode, defcode, name=funcname, nd=nd)
257
+
258
+ buf_ptr_type_code = self.buf_ptr_type.empty_declaration_code()
259
+ ptrcode = "%s(%s, %s, %s)" % (funcname, buf_ptr_type_code, self.buf_ptr,
260
+ ", ".join(params))
261
+ return ptrcode
262
+
263
+
264
+ def get_flags(buffer_aux, buffer_type):
265
+ flags = 'PyBUF_FORMAT'
266
+ mode = buffer_type.mode
267
+ if mode == 'full':
268
+ flags += '| PyBUF_INDIRECT'
269
+ elif mode == 'strided':
270
+ flags += '| PyBUF_STRIDES'
271
+ elif mode == 'c':
272
+ flags += '| PyBUF_C_CONTIGUOUS'
273
+ elif mode == 'fortran':
274
+ flags += '| PyBUF_F_CONTIGUOUS'
275
+ else:
276
+ assert False
277
+ if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE"
278
+ return flags
279
+
280
+ def used_buffer_aux_vars(entry):
281
+ buffer_aux = entry.buffer_aux
282
+ buffer_aux.buflocal_nd_var.used = True
283
+ buffer_aux.rcbuf_var.used = True
284
+
285
+ def put_unpack_buffer_aux_into_scope(buf_entry, code):
286
+ # Generate code to copy the needed struct info into local
287
+ # variables.
288
+ buffer_aux, mode = buf_entry.buffer_aux, buf_entry.type.mode
289
+ pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
290
+
291
+ fldnames = ['strides', 'shape']
292
+ if mode == 'full':
293
+ fldnames.append('suboffsets')
294
+
295
+ ln = []
296
+ for i in range(buf_entry.type.ndim):
297
+ for fldname in fldnames:
298
+ ln.append("%s.diminfo[%d].%s = %s.rcbuffer->pybuffer.%s[%d];" % (
299
+ pybuffernd_struct, i, fldname,
300
+ pybuffernd_struct, fldname, i,
301
+ ))
302
+ code.putln(' '.join(ln))
303
+
304
+ def put_init_vars(entry, code):
305
+ bufaux = entry.buffer_aux
306
+ pybuffernd_struct = bufaux.buflocal_nd_var.cname
307
+ pybuffer_struct = bufaux.rcbuf_var.cname
308
+ # init pybuffer_struct
309
+ code.putln("%s.pybuffer.buf = NULL;" % pybuffer_struct)
310
+ code.putln("%s.refcount = 0;" % pybuffer_struct)
311
+ # init the buffer object
312
+ # code.put_init_var_to_py_none(entry)
313
+ # init the pybuffernd_struct
314
+ code.putln("%s.data = NULL;" % pybuffernd_struct)
315
+ code.putln("%s.rcbuffer = &%s;" % (pybuffernd_struct, pybuffer_struct))
316
+
317
+
318
+ def put_acquire_arg_buffer(entry, code, pos):
319
+ buffer_aux = entry.buffer_aux
320
+ getbuffer = get_getbuffer_call(code, entry.cname, buffer_aux, entry.type)
321
+
322
+ # Acquire any new buffer
323
+ code.putln("{")
324
+ code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % entry.type.dtype.struct_nesting_depth())
325
+ code.putln(code.error_goto_if("%s == -1" % getbuffer, pos))
326
+ code.putln("}")
327
+ # An exception raised in arg parsing cannot be caught, so no
328
+ # need to care about the buffer then.
329
+ put_unpack_buffer_aux_into_scope(entry, code)
330
+
331
+
332
+ def put_release_buffer_code(code, entry):
333
+ code.globalstate.use_utility_code(acquire_utility_code)
334
+ code.putln("__Pyx_SafeReleaseBuffer(&%s.rcbuffer->pybuffer);" % entry.buffer_aux.buflocal_nd_var.cname)
335
+
336
+
337
+ def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type):
338
+ ndim = buffer_type.ndim
339
+ cast = int(buffer_type.cast)
340
+ flags = get_flags(buffer_aux, buffer_type)
341
+ pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
342
+
343
+ dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype)
344
+
345
+ code.globalstate.use_utility_code(acquire_utility_code)
346
+ return ("__Pyx_GetBufferAndValidate(&%(pybuffernd_struct)s.rcbuffer->pybuffer, "
347
+ "(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, "
348
+ "%(cast)d, __pyx_stack)" % locals())
349
+
350
+
351
+ def put_assign_to_buffer(lhs_cname, rhs_cname, buf_entry,
352
+ is_initialized, pos, code):
353
+ """
354
+ Generate code for reassigning a buffer variables. This only deals with getting
355
+ the buffer auxiliary structure and variables set up correctly, the assignment
356
+ itself and refcounting is the responsibility of the caller.
357
+
358
+ However, the assignment operation may throw an exception so that the reassignment
359
+ never happens.
360
+
361
+ Depending on the circumstances there are two possible outcomes:
362
+ - Old buffer released, new acquired, rhs assigned to lhs
363
+ - Old buffer released, new acquired which fails, reaqcuire old lhs buffer
364
+ (which may or may not succeed).
365
+ """
366
+
367
+ buffer_aux, buffer_type = buf_entry.buffer_aux, buf_entry.type
368
+ pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
369
+ flags = get_flags(buffer_aux, buffer_type)
370
+
371
+ code.putln("{") # Set up necessary stack for getbuffer
372
+ code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())
373
+
374
+ getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below
375
+
376
+ if is_initialized:
377
+ # Release any existing buffer
378
+ code.putln('__Pyx_SafeReleaseBuffer(&%s.rcbuffer->pybuffer);' % pybuffernd_struct)
379
+ # Acquire
380
+ retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
381
+ code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
382
+ code.putln('if (%s) {' % (code.unlikely("%s < 0" % retcode_cname)))
383
+ # If acquisition failed, attempt to reacquire the old buffer
384
+ # before raising the exception. A failure of reacquisition
385
+ # will cause the reacquisition exception to be reported, one
386
+ # can consider working around this later.
387
+ exc_temps = tuple(code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
388
+ for _ in range(3))
389
+ code.putln('PyErr_Fetch(&%s, &%s, &%s);' % exc_temps)
390
+ code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
391
+ code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % exc_temps) # Do not refnanny these!
392
+ code.globalstate.use_utility_code(raise_buffer_fallback_code)
393
+ code.putln('__Pyx_RaiseBufferFallbackError();')
394
+ code.putln('} else {')
395
+ code.putln('PyErr_Restore(%s, %s, %s);' % exc_temps)
396
+ code.putln('}')
397
+ code.putln('%s = %s = %s = 0;' % exc_temps)
398
+ for t in exc_temps:
399
+ code.funcstate.release_temp(t)
400
+ code.putln('}')
401
+ # Unpack indices
402
+ put_unpack_buffer_aux_into_scope(buf_entry, code)
403
+ code.putln(code.error_goto_if_neg(retcode_cname, pos))
404
+ code.funcstate.release_temp(retcode_cname)
405
+ else:
406
+ # Our entry had no previous value, so set to None when acquisition fails.
407
+ # In this case, auxiliary vars should be set up right in initialization to a zero-buffer,
408
+ # so it suffices to set the buf field to NULL.
409
+ code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % rhs_cname)))
410
+ code.putln('%s = %s; __Pyx_INCREF(Py_None); %s.rcbuffer->pybuffer.buf = NULL;' %
411
+ (lhs_cname,
412
+ PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
413
+ pybuffernd_struct))
414
+ code.putln(code.error_goto(pos))
415
+ code.put('} else {')
416
+ # Unpack indices
417
+ put_unpack_buffer_aux_into_scope(buf_entry, code)
418
+ code.putln('}')
419
+
420
+ code.putln("}") # Release stack
421
+
422
+
423
+ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives,
424
+ pos, code, negative_indices, in_nogil_context):
425
+ """
426
+ Generates code to process indices and calculate an offset into
427
+ a buffer. Returns a C string which gives a pointer which can be
428
+ read from or written to at will (it is an expression so caller should
429
+ store it in a temporary if it is used more than once).
430
+
431
+ As the bounds checking can have any number of combinations of unsigned
432
+ arguments, smart optimizations etc. we insert it directly in the function
433
+ body. The lookup however is delegated to a inline function that is instantiated
434
+ once per ndim (lookup with suboffsets tend to get quite complicated).
435
+
436
+ entry is a BufferEntry
437
+ """
438
+ negative_indices = directives['wraparound'] and negative_indices
439
+
440
+ if directives['boundscheck']:
441
+ # Check bounds and fix negative indices.
442
+ # We allocate a temporary which is initialized to -1, meaning OK (!).
443
+ # If an error occurs, the temp is set to the index dimension the
444
+ # error is occurring at.
445
+ failed_dim_temp = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
446
+ code.putln("%s = -1;" % failed_dim_temp)
447
+ for dim, (signed, cname, shape) in enumerate(zip(index_signeds, index_cnames, entry.get_buf_shapevars())):
448
+ if signed != 0:
449
+ # not unsigned, deal with negative index
450
+ code.putln("if (%s < 0) {" % cname)
451
+ if negative_indices:
452
+ code.putln("%s += %s;" % (cname, shape))
453
+ code.putln("if (%s) %s = %d;" % (
454
+ code.unlikely("%s < 0" % cname),
455
+ failed_dim_temp, dim))
456
+ else:
457
+ code.putln("%s = %d;" % (failed_dim_temp, dim))
458
+ code.put("} else ")
459
+ # check bounds in positive direction
460
+ if signed != 0:
461
+ cast = ""
462
+ else:
463
+ cast = "(size_t)"
464
+ code.putln("if (%s) %s = %d;" % (
465
+ code.unlikely("%s >= %s%s" % (cname, cast, shape)),
466
+ failed_dim_temp, dim))
467
+
468
+ if in_nogil_context:
469
+ code.globalstate.use_utility_code(raise_indexerror_nogil)
470
+ func = '__Pyx_RaiseBufferIndexErrorNogil'
471
+ else:
472
+ code.globalstate.use_utility_code(raise_indexerror_code)
473
+ func = '__Pyx_RaiseBufferIndexError'
474
+
475
+ code.putln("if (%s) {" % code.unlikely("%s != -1" % failed_dim_temp))
476
+ code.putln('%s(%s);' % (func, failed_dim_temp))
477
+ code.putln(code.error_goto(pos))
478
+ code.putln('}')
479
+ code.funcstate.release_temp(failed_dim_temp)
480
+ elif negative_indices:
481
+ # Only fix negative indices.
482
+ for signed, cname, shape in zip(index_signeds, index_cnames, entry.get_buf_shapevars()):
483
+ if signed != 0:
484
+ code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape))
485
+
486
+ return entry.generate_buffer_lookup_code(code, index_cnames)
487
+
488
+
489
+ def use_bufstruct_declare_code(env):
490
+ env.use_utility_code(buffer_struct_declare_code)
491
+
492
+
493
+ def buf_lookup_full_code(proto, defin, name, nd):
494
+ """
495
+ Generates a buffer lookup function for the right number
496
+ of dimensions. The function gives back a void* at the right location.
497
+ """
498
+ # _i_ndex, _s_tride, sub_o_ffset
499
+ macroargs = ", ".join(["i%d, s%d, o%d" % (i, i, i) for i in range(nd)])
500
+ proto.putln("#define %s(type, buf, %s) (type)(%s_imp(buf, %s))" % (name, macroargs, name, macroargs))
501
+
502
+ funcargs = ", ".join(["Py_ssize_t i%d, Py_ssize_t s%d, Py_ssize_t o%d" % (i, i, i) for i in range(nd)])
503
+ proto.putln("static CYTHON_INLINE void* %s_imp(void* buf, %s);" % (name, funcargs))
504
+ defin.putln(dedent("""
505
+ static CYTHON_INLINE void* %s_imp(void* buf, %s) {
506
+ char* ptr = (char*)buf;
507
+ """) % (name, funcargs) + "".join([dedent("""\
508
+ ptr += s%d * i%d;
509
+ if (o%d >= 0) ptr = *((char**)ptr) + o%d;
510
+ """) % (i, i, i, i) for i in range(nd)]
511
+ ) + "\nreturn ptr;\n}")
512
+
513
+
514
+ def buf_lookup_strided_code(proto, defin, name, nd):
515
+ """
516
+ Generates a buffer lookup function for the right number
517
+ of dimensions. The function gives back a void* at the right location.
518
+ """
519
+ # _i_ndex, _s_tride
520
+ args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
521
+ offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd)])
522
+ proto.putln("#define %s(type, buf, %s) (type)((char*)buf + %s)" % (name, args, offset))
523
+
524
+
525
+ def buf_lookup_c_code(proto, defin, name, nd):
526
+ """
527
+ Similar to strided lookup, but can assume that the last dimension
528
+ doesn't need a multiplication as long as.
529
+ Still we keep the same signature for now.
530
+ """
531
+ if nd == 1:
532
+ proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
533
+ else:
534
+ args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
535
+ offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd - 1)])
536
+ proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, nd - 1))
537
+
538
+
539
+ def buf_lookup_fortran_code(proto, defin, name, nd):
540
+ """
541
+ Like C lookup, but the first index is optimized instead.
542
+ """
543
+ if nd == 1:
544
+ proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
545
+ else:
546
+ args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
547
+ offset = " + ".join(["i%d * s%d" % (i, i) for i in range(1, nd)])
548
+ proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, 0))
549
+
550
+
551
+ def mangle_dtype_name(dtype):
552
+ # Use prefixes to separate user defined types from builtins
553
+ # (consider "typedef float unsigned_int")
554
+ if dtype.is_pyobject:
555
+ return "object"
556
+ elif dtype.is_ptr:
557
+ return "ptr"
558
+ else:
559
+ if dtype.is_typedef or dtype.is_struct_or_union:
560
+ prefix = "nn_"
561
+ else:
562
+ prefix = ""
563
+ return prefix + dtype.specialization_name()
564
+
565
+ def get_type_information_cname(code, dtype, maxdepth=None):
566
+ """
567
+ Output the run-time type information (__Pyx_TypeInfo) for given dtype,
568
+ and return the name of the type info struct.
569
+
570
+ Structs with two floats of the same size are encoded as complex numbers.
571
+ One can separate between complex numbers declared as struct or with native
572
+ encoding by inspecting to see if the fields field of the type is
573
+ filled in.
574
+ """
575
+ namesuffix = mangle_dtype_name(dtype)
576
+ name = "__Pyx_TypeInfo_%s" % namesuffix
577
+ structinfo_name = "__Pyx_StructFields_%s" % namesuffix
578
+
579
+ if dtype.is_error: return "<error>"
580
+
581
+ # It's critical that walking the type info doesn't use more stack
582
+ # depth than dtype.struct_nesting_depth() returns, so use an assertion for this
583
+ if maxdepth is None: maxdepth = dtype.struct_nesting_depth()
584
+ if maxdepth <= 0:
585
+ assert False
586
+
587
+ if name not in code.globalstate.utility_codes:
588
+ code.globalstate.utility_codes.add(name)
589
+ typecode = code.globalstate['typeinfo']
590
+
591
+ arraysizes = []
592
+ if dtype.is_array:
593
+ while dtype.is_array:
594
+ arraysizes.append(dtype.size)
595
+ dtype = dtype.base_type
596
+
597
+ complex_possible = dtype.is_struct_or_union and dtype.can_be_complex()
598
+
599
+ declcode = dtype.empty_declaration_code()
600
+ if dtype.is_simple_buffer_dtype():
601
+ structinfo_name = "NULL"
602
+ elif dtype.is_struct:
603
+ struct_scope = dtype.scope
604
+ if dtype.is_cv_qualified:
605
+ struct_scope = struct_scope.base_type_scope
606
+ # Must pre-call all used types in order not to recurse during utility code writing.
607
+ fields = struct_scope.var_entries
608
+ assert len(fields) > 0
609
+ types = [get_type_information_cname(code, f.type, maxdepth - 1)
610
+ for f in fields]
611
+ typecode.putln("static const __Pyx_StructField %s[] = {" % structinfo_name, safe=True)
612
+
613
+ if dtype.is_cv_qualified:
614
+ # roughly speaking, remove "const" from struct_type
615
+ struct_type = dtype.cv_base_type.empty_declaration_code()
616
+ else:
617
+ struct_type = dtype.empty_declaration_code()
618
+
619
+ for f, typeinfo in zip(fields, types):
620
+ typecode.putln(' {&%s, "%s", offsetof(%s, %s)},' %
621
+ (typeinfo, f.name, struct_type, f.cname), safe=True)
622
+
623
+ typecode.putln(' {NULL, NULL, 0}', safe=True)
624
+ typecode.putln("};", safe=True)
625
+ else:
626
+ assert False
627
+
628
+ rep = str(dtype)
629
+
630
+ flags = "0"
631
+ is_unsigned = "0"
632
+ if dtype is PyrexTypes.c_char_type:
633
+ is_unsigned = "__PYX_IS_UNSIGNED(%s)" % declcode
634
+ typegroup = "'H'"
635
+ elif dtype.is_int:
636
+ is_unsigned = "__PYX_IS_UNSIGNED(%s)" % declcode
637
+ typegroup = "%s ? 'U' : 'I'" % is_unsigned
638
+ elif complex_possible or dtype.is_complex:
639
+ typegroup = "'C'"
640
+ elif dtype.is_float:
641
+ typegroup = "'R'"
642
+ elif dtype.is_struct:
643
+ typegroup = "'S'"
644
+ if dtype.packed:
645
+ flags = "__PYX_BUF_FLAGS_PACKED_STRUCT"
646
+ elif dtype.is_pyobject:
647
+ typegroup = "'O'"
648
+ else:
649
+ assert False, dtype
650
+
651
+ typeinfo = ('static const __Pyx_TypeInfo %s = '
652
+ '{ "%s", %s, sizeof(%s), { %s }, %s, %s, %s, %s };')
653
+ tup = (name, rep, structinfo_name, declcode,
654
+ ', '.join([str(x) for x in arraysizes]) or '0', len(arraysizes),
655
+ typegroup, is_unsigned, flags)
656
+ typecode.putln(typeinfo % tup, safe=True)
657
+
658
+ return name
659
+
660
+ def load_buffer_utility(util_code_name, context=None, **kwargs):
661
+ if context is None:
662
+ return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
663
+ else:
664
+ return TempitaUtilityCode.load(util_code_name, "Buffer.c", context=context, **kwargs)
665
+
666
+ context = dict(max_dims=Options.buffer_max_dims)
667
+ buffer_struct_declare_code = load_buffer_utility("BufferStructDeclare", context=context)
668
+ buffer_formats_declare_code = load_buffer_utility("BufferFormatStructs")
669
+
670
+ # Utility function to set the right exception
671
+ # The caller should immediately goto_error
672
+ raise_indexerror_code = load_buffer_utility("BufferIndexError")
673
+ raise_indexerror_nogil = load_buffer_utility("BufferIndexErrorNogil")
674
+ raise_buffer_fallback_code = load_buffer_utility("BufferFallbackError")
675
+
676
+ acquire_utility_code = load_buffer_utility("BufferGetAndValidate", context=context)
677
+ buffer_format_check_code = load_buffer_utility("BufferFormatCheck", context=context)
678
+
679
+ # See utility code BufferFormatFromTypeInfo
680
+ _typeinfo_to_format_code = load_buffer_utility("TypeInfoToFormat")