Cython 3.3.0__cp315-cp315-win_amd64.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 (339) hide show
  1. Cython/Build/BuildExecutable.py +156 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +349 -0
  4. Cython/Build/Dependencies.py +1281 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +467 -0
  7. Cython/Build/IpythonMagic.py +559 -0
  8. Cython/Build/SharedModule.py +165 -0
  9. Cython/Build/Tests/TestCyCache.py +195 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +480 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +303 -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 +825 -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 +679 -0
  23. Cython/Compiler/Builtin.py +1102 -0
  24. Cython/Compiler/CmdLine.py +373 -0
  25. Cython/Compiler/Code.cp315-win_amd64.pyd +0 -0
  26. Cython/Compiler/Code.pxd +154 -0
  27. Cython/Compiler/Code.py +3760 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +208 -0
  30. Cython/Compiler/Dataclass.py +890 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +310 -0
  33. Cython/Compiler/ExprNodes.py +16273 -0
  34. Cython/Compiler/FlowControl.cp315-win_amd64.pyd +0 -0
  35. Cython/Compiler/FlowControl.pxd +112 -0
  36. Cython/Compiler/FlowControl.py +1573 -0
  37. Cython/Compiler/FusedNode.cp315-win_amd64.pyd +0 -0
  38. Cython/Compiler/FusedNode.py +978 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +422 -0
  42. Cython/Compiler/LineTable.cp315-win_amd64.pyd +0 -0
  43. Cython/Compiler/LineTable.py +114 -0
  44. Cython/Compiler/Main.py +856 -0
  45. Cython/Compiler/MatchCaseNodes.py +2200 -0
  46. Cython/Compiler/MemoryView.py +930 -0
  47. Cython/Compiler/ModuleNode.py +4548 -0
  48. Cython/Compiler/Naming.py +370 -0
  49. Cython/Compiler/Nodes.py +11304 -0
  50. Cython/Compiler/Optimize.py +5564 -0
  51. Cython/Compiler/Options.py +840 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +80 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4808 -0
  54. Cython/Compiler/Parsing.cp315-win_amd64.pyd +0 -0
  55. Cython/Compiler/Parsing.pxd +9 -0
  56. Cython/Compiler/Parsing.py +4809 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +6588 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.cp315-win_amd64.pyd +0 -0
  61. Cython/Compiler/Scanning.pxd +70 -0
  62. Cython/Compiler/Scanning.py +720 -0
  63. Cython/Compiler/StringEncoding.cp315-win_amd64.pyd +0 -0
  64. Cython/Compiler/StringEncoding.py +354 -0
  65. Cython/Compiler/Symtab.py +3121 -0
  66. Cython/Compiler/Tests/TestBuffer.py +105 -0
  67. Cython/Compiler/Tests/TestBuiltin.py +196 -0
  68. Cython/Compiler/Tests/TestCmdLine.py +652 -0
  69. Cython/Compiler/Tests/TestCode.py +145 -0
  70. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  71. Cython/Compiler/Tests/TestGrammar.py +202 -0
  72. Cython/Compiler/Tests/TestMemView.py +71 -0
  73. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  74. Cython/Compiler/Tests/TestScanning.py +132 -0
  75. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  76. Cython/Compiler/Tests/TestStringEncoding.py +20 -0
  77. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  78. Cython/Compiler/Tests/TestTreePath.py +103 -0
  79. Cython/Compiler/Tests/TestTypes.py +119 -0
  80. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  81. Cython/Compiler/Tests/TestVisitor.py +119 -0
  82. Cython/Compiler/Tests/Utils.py +36 -0
  83. Cython/Compiler/Tests/__init__.py +1 -0
  84. Cython/Compiler/TreeFragment.py +279 -0
  85. Cython/Compiler/TreePath.py +303 -0
  86. Cython/Compiler/TypeInference.py +611 -0
  87. Cython/Compiler/TypeSlots.py +1329 -0
  88. Cython/Compiler/UFuncs.py +317 -0
  89. Cython/Compiler/UtilNodes.py +389 -0
  90. Cython/Compiler/UtilityCode.py +354 -0
  91. Cython/Compiler/Version.py +8 -0
  92. Cython/Compiler/Visitor.cp315-win_amd64.pyd +0 -0
  93. Cython/Compiler/Visitor.pxd +52 -0
  94. Cython/Compiler/Visitor.py +914 -0
  95. Cython/Compiler/__init__.py +1 -0
  96. Cython/Coverage.py +448 -0
  97. Cython/Debugger/Cygdb.py +214 -0
  98. Cython/Debugger/DebugWriter.py +82 -0
  99. Cython/Debugger/Tests/TestLibCython.py +280 -0
  100. Cython/Debugger/Tests/__init__.py +1 -0
  101. Cython/Debugger/Tests/cfuncs.c +8 -0
  102. Cython/Debugger/Tests/codefile +49 -0
  103. Cython/Debugger/Tests/test_libcython_in_gdb.py +580 -0
  104. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  105. Cython/Debugger/__init__.py +1 -0
  106. Cython/Debugger/libcython.py +1548 -0
  107. Cython/Debugger/libpython.py +2821 -0
  108. Cython/Debugging.py +20 -0
  109. Cython/Distutils/__init__.py +2 -0
  110. Cython/Distutils/build_ext.py +143 -0
  111. Cython/Distutils/extension.py +96 -0
  112. Cython/Distutils/old_build_ext.py +351 -0
  113. Cython/Includes/cpython/__init__.pxd +173 -0
  114. Cython/Includes/cpython/array.pxd +152 -0
  115. Cython/Includes/cpython/bool.pxd +37 -0
  116. Cython/Includes/cpython/buffer.pxd +112 -0
  117. Cython/Includes/cpython/bytearray.pxd +33 -0
  118. Cython/Includes/cpython/bytes.pxd +200 -0
  119. Cython/Includes/cpython/cellobject.pxd +35 -0
  120. Cython/Includes/cpython/ceval.pxd +8 -0
  121. Cython/Includes/cpython/codecs.pxd +121 -0
  122. Cython/Includes/cpython/complex.pxd +60 -0
  123. Cython/Includes/cpython/contextvars.pxd +145 -0
  124. Cython/Includes/cpython/conversion.pxd +36 -0
  125. Cython/Includes/cpython/datetime.pxd +395 -0
  126. Cython/Includes/cpython/descr.pxd +26 -0
  127. Cython/Includes/cpython/dict.pxd +268 -0
  128. Cython/Includes/cpython/exc.pxd +263 -0
  129. Cython/Includes/cpython/fileobject.pxd +57 -0
  130. Cython/Includes/cpython/float.pxd +56 -0
  131. Cython/Includes/cpython/frozendict.pxd +37 -0
  132. Cython/Includes/cpython/function.pxd +65 -0
  133. Cython/Includes/cpython/genobject.pxd +25 -0
  134. Cython/Includes/cpython/getargs.pxd +12 -0
  135. Cython/Includes/cpython/instance.pxd +25 -0
  136. Cython/Includes/cpython/iterator.pxd +36 -0
  137. Cython/Includes/cpython/iterobject.pxd +24 -0
  138. Cython/Includes/cpython/list.pxd +144 -0
  139. Cython/Includes/cpython/long.pxd +180 -0
  140. Cython/Includes/cpython/longintrepr.pxd +14 -0
  141. Cython/Includes/cpython/mapping.pxd +63 -0
  142. Cython/Includes/cpython/marshal.pxd +66 -0
  143. Cython/Includes/cpython/mem.pxd +120 -0
  144. Cython/Includes/cpython/memoryview.pxd +50 -0
  145. Cython/Includes/cpython/method.pxd +49 -0
  146. Cython/Includes/cpython/module.pxd +208 -0
  147. Cython/Includes/cpython/number.pxd +258 -0
  148. Cython/Includes/cpython/object.pxd +430 -0
  149. Cython/Includes/cpython/pycapsule.pxd +143 -0
  150. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  151. Cython/Includes/cpython/pyport.pxd +8 -0
  152. Cython/Includes/cpython/pystate.pxd +95 -0
  153. Cython/Includes/cpython/pythread.pxd +53 -0
  154. Cython/Includes/cpython/ref.pxd +141 -0
  155. Cython/Includes/cpython/sentinel.pxd +17 -0
  156. Cython/Includes/cpython/sequence.pxd +134 -0
  157. Cython/Includes/cpython/set.pxd +119 -0
  158. Cython/Includes/cpython/slice.pxd +70 -0
  159. Cython/Includes/cpython/time.pxd +129 -0
  160. Cython/Includes/cpython/tuple.pxd +72 -0
  161. Cython/Includes/cpython/type.pxd +146 -0
  162. Cython/Includes/cpython/unicode.pxd +639 -0
  163. Cython/Includes/cpython/version.pxd +32 -0
  164. Cython/Includes/cpython/weakref.pxd +78 -0
  165. Cython/Includes/libc/__init__.pxd +1 -0
  166. Cython/Includes/libc/complex.pxd +35 -0
  167. Cython/Includes/libc/errno.pxd +127 -0
  168. Cython/Includes/libc/float.pxd +43 -0
  169. Cython/Includes/libc/limits.pxd +28 -0
  170. Cython/Includes/libc/locale.pxd +46 -0
  171. Cython/Includes/libc/math.pxd +209 -0
  172. Cython/Includes/libc/setjmp.pxd +10 -0
  173. Cython/Includes/libc/signal.pxd +64 -0
  174. Cython/Includes/libc/stddef.pxd +9 -0
  175. Cython/Includes/libc/stdint.pxd +105 -0
  176. Cython/Includes/libc/stdio.pxd +80 -0
  177. Cython/Includes/libc/stdlib.pxd +72 -0
  178. Cython/Includes/libc/string.pxd +50 -0
  179. Cython/Includes/libc/threads.pxd +234 -0
  180. Cython/Includes/libc/time.pxd +52 -0
  181. Cython/Includes/libcpp/__init__.pxd +4 -0
  182. Cython/Includes/libcpp/algorithm.pxd +320 -0
  183. Cython/Includes/libcpp/any.pxd +16 -0
  184. Cython/Includes/libcpp/atomic.pxd +59 -0
  185. Cython/Includes/libcpp/barrier.pxd +22 -0
  186. Cython/Includes/libcpp/bit.pxd +29 -0
  187. Cython/Includes/libcpp/cast.pxd +12 -0
  188. Cython/Includes/libcpp/cmath.pxd +518 -0
  189. Cython/Includes/libcpp/complex.pxd +106 -0
  190. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  191. Cython/Includes/libcpp/deque.pxd +165 -0
  192. Cython/Includes/libcpp/exception.pxd +216 -0
  193. Cython/Includes/libcpp/execution.pxd +15 -0
  194. Cython/Includes/libcpp/forward_list.pxd +63 -0
  195. Cython/Includes/libcpp/functional.pxd +26 -0
  196. Cython/Includes/libcpp/future.pxd +103 -0
  197. Cython/Includes/libcpp/iterator.pxd +34 -0
  198. Cython/Includes/libcpp/latch.pxd +17 -0
  199. Cython/Includes/libcpp/limits.pxd +61 -0
  200. Cython/Includes/libcpp/list.pxd +117 -0
  201. Cython/Includes/libcpp/map.pxd +252 -0
  202. Cython/Includes/libcpp/memory.pxd +115 -0
  203. Cython/Includes/libcpp/mutex.pxd +387 -0
  204. Cython/Includes/libcpp/numbers.pxd +15 -0
  205. Cython/Includes/libcpp/numeric.pxd +131 -0
  206. Cython/Includes/libcpp/optional.pxd +34 -0
  207. Cython/Includes/libcpp/pair.pxd +1 -0
  208. Cython/Includes/libcpp/queue.pxd +25 -0
  209. Cython/Includes/libcpp/random.pxd +166 -0
  210. Cython/Includes/libcpp/semaphore.pxd +43 -0
  211. Cython/Includes/libcpp/set.pxd +228 -0
  212. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  213. Cython/Includes/libcpp/span.pxd +87 -0
  214. Cython/Includes/libcpp/stack.pxd +11 -0
  215. Cython/Includes/libcpp/stop_token.pxd +117 -0
  216. Cython/Includes/libcpp/string.pxd +355 -0
  217. Cython/Includes/libcpp/string_view.pxd +183 -0
  218. Cython/Includes/libcpp/typeindex.pxd +15 -0
  219. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  220. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  221. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  222. Cython/Includes/libcpp/utility.pxd +30 -0
  223. Cython/Includes/libcpp/vector.pxd +186 -0
  224. Cython/Includes/numpy/math.pxd +150 -0
  225. Cython/Includes/openmp.pxd +50 -0
  226. Cython/Includes/posix/__init__.pxd +1 -0
  227. Cython/Includes/posix/dlfcn.pxd +14 -0
  228. Cython/Includes/posix/fcntl.pxd +86 -0
  229. Cython/Includes/posix/ioctl.pxd +4 -0
  230. Cython/Includes/posix/mman.pxd +101 -0
  231. Cython/Includes/posix/resource.pxd +57 -0
  232. Cython/Includes/posix/select.pxd +21 -0
  233. Cython/Includes/posix/signal.pxd +73 -0
  234. Cython/Includes/posix/stat.pxd +98 -0
  235. Cython/Includes/posix/stdio.pxd +37 -0
  236. Cython/Includes/posix/stdlib.pxd +29 -0
  237. Cython/Includes/posix/strings.pxd +9 -0
  238. Cython/Includes/posix/time.pxd +71 -0
  239. Cython/Includes/posix/types.pxd +30 -0
  240. Cython/Includes/posix/uio.pxd +26 -0
  241. Cython/Includes/posix/unistd.pxd +271 -0
  242. Cython/Includes/posix/wait.pxd +38 -0
  243. Cython/LZSS.cp315-win_amd64.pyd +0 -0
  244. Cython/LZSS.py +184 -0
  245. Cython/Plex/Actions.cp315-win_amd64.pyd +0 -0
  246. Cython/Plex/Actions.pxd +24 -0
  247. Cython/Plex/Actions.py +119 -0
  248. Cython/Plex/DFA.cp315-win_amd64.pyd +0 -0
  249. Cython/Plex/DFA.pxd +14 -0
  250. Cython/Plex/DFA.py +164 -0
  251. Cython/Plex/Errors.py +48 -0
  252. Cython/Plex/Lexicons.py +178 -0
  253. Cython/Plex/Machines.cp315-win_amd64.pyd +0 -0
  254. Cython/Plex/Machines.pxd +36 -0
  255. Cython/Plex/Machines.py +238 -0
  256. Cython/Plex/Regexps.py +535 -0
  257. Cython/Plex/Scanners.cp315-win_amd64.pyd +0 -0
  258. Cython/Plex/Scanners.pxd +45 -0
  259. Cython/Plex/Scanners.py +328 -0
  260. Cython/Plex/Transitions.cp315-win_amd64.pyd +0 -0
  261. Cython/Plex/Transitions.pxd +14 -0
  262. Cython/Plex/Transitions.py +239 -0
  263. Cython/Plex/__init__.py +34 -0
  264. Cython/Runtime/__init__.py +1 -0
  265. Cython/Runtime/refnanny.cp315-win_amd64.pyd +0 -0
  266. Cython/Runtime/refnanny.pyx +237 -0
  267. Cython/Shadow.py +1174 -0
  268. Cython/StringIOTree.cp315-win_amd64.pyd +0 -0
  269. Cython/StringIOTree.py +169 -0
  270. Cython/Tempita/__init__.py +4 -0
  271. Cython/Tempita/_looper.py +154 -0
  272. Cython/Tempita/_tempita.cp315-win_amd64.pyd +0 -0
  273. Cython/Tempita/_tempita.py +1087 -0
  274. Cython/TestUtils.py +472 -0
  275. Cython/Tests/TestCodeWriter.py +128 -0
  276. Cython/Tests/TestCythonUtils.py +202 -0
  277. Cython/Tests/TestJediTyper.py +223 -0
  278. Cython/Tests/TestShadow.py +125 -0
  279. Cython/Tests/TestStringIOTree.py +68 -0
  280. Cython/Tests/TestTestUtils.py +89 -0
  281. Cython/Tests/__init__.py +1 -0
  282. Cython/Tests/xmlrunner.py +390 -0
  283. Cython/Utility/AsyncGen.c +1152 -0
  284. Cython/Utility/Buffer.c +866 -0
  285. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  286. Cython/Utility/Builtins.c +1068 -0
  287. Cython/Utility/CConvert.pyx +153 -0
  288. Cython/Utility/CMath.c +104 -0
  289. Cython/Utility/CommonStructures.c +244 -0
  290. Cython/Utility/Complex.c +378 -0
  291. Cython/Utility/Coroutine.c +2344 -0
  292. Cython/Utility/CpdefEnums.pyx +119 -0
  293. Cython/Utility/CppConvert.pyx +282 -0
  294. Cython/Utility/CppSupport.cpp +151 -0
  295. Cython/Utility/CythonFunction.c +2185 -0
  296. Cython/Utility/Dataclasses.c +101 -0
  297. Cython/Utility/Embed.c +129 -0
  298. Cython/Utility/Exceptions.c +1331 -0
  299. Cython/Utility/Exceptions_Cy.pyx +109 -0
  300. Cython/Utility/ExtensionTypes.c +1199 -0
  301. Cython/Utility/FunctionArguments.c +1052 -0
  302. Cython/Utility/FusedFunction.pyx +44 -0
  303. Cython/Utility/ImportExport.c +972 -0
  304. Cython/Utility/MatchCase.c +981 -0
  305. Cython/Utility/MatchCase_Cy.pyx +12 -0
  306. Cython/Utility/MemoryView.pxd +108 -0
  307. Cython/Utility/MemoryView.pyx +1499 -0
  308. Cython/Utility/MemoryView_C.c +1056 -0
  309. Cython/Utility/ModuleSetupCode.c +3319 -0
  310. Cython/Utility/NumpyImportArray.c +46 -0
  311. Cython/Utility/ObjectHandling.c +3404 -0
  312. Cython/Utility/Optimize.c +2564 -0
  313. Cython/Utility/Overflow.c +378 -0
  314. Cython/Utility/Profile.c +736 -0
  315. Cython/Utility/StringTools.c +1534 -0
  316. Cython/Utility/Synchronization.c +438 -0
  317. Cython/Utility/TString.c +369 -0
  318. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  319. Cython/Utility/TestCythonScope.pyx +75 -0
  320. Cython/Utility/TestUtilityLoader.c +12 -0
  321. Cython/Utility/TypeConversion.c +1588 -0
  322. Cython/Utility/UFuncs.pyx +50 -0
  323. Cython/Utility/UFuncs_C.c +89 -0
  324. Cython/Utility/__init__.py +28 -0
  325. Cython/Utility/arrayarray.h +172 -0
  326. Cython/Utils.cp315-win_amd64.pyd +0 -0
  327. Cython/Utils.py +680 -0
  328. Cython/__init__.py +12 -0
  329. Cython/_shared.cp315-win_amd64.pyd +0 -0
  330. Cython/py.typed +0 -0
  331. cython-3.3.0.dist-info/METADATA +555 -0
  332. cython-3.3.0.dist-info/RECORD +339 -0
  333. cython-3.3.0.dist-info/WHEEL +5 -0
  334. cython-3.3.0.dist-info/entry_points.txt +4 -0
  335. cython-3.3.0.dist-info/top_level.txt +3 -0
  336. cython.py +29 -0
  337. pyximport/__init__.py +4 -0
  338. pyximport/pyxbuild.py +160 -0
  339. pyximport/pyximport.py +482 -0
@@ -0,0 +1,890 @@
1
+ # functions to transform a c class into a dataclass
2
+
3
+ from collections import OrderedDict
4
+ from textwrap import dedent
5
+ import operator
6
+
7
+ from . import ExprNodes
8
+ from . import Nodes
9
+ from . import PyrexTypes
10
+ from . import Builtin
11
+ from . import Naming
12
+ from .Errors import error, warning
13
+ from .Code import UtilityCode, PyxCodeWriter
14
+ from .Visitor import VisitorTransform
15
+ from .StringEncoding import EncodedString
16
+ from .TreeFragment import TreeFragment
17
+ from .ParseTreeTransforms import NormalizeTree, SkipDeclarations, InterpretCompilerDirectives
18
+ from .Options import copy_inherited_directives
19
+
20
+ def make_dataclasses_module_callnode(pos):
21
+ dataclass_loader_utilitycode = UtilityCode.load_cached(
22
+ "LoadDataclassesModule", "Dataclasses.c")
23
+ return ExprNodes.PythonCapiCallNode(
24
+ pos, "__Pyx_Load_dataclasses_Module",
25
+ PyrexTypes.CFuncType(PyrexTypes.py_object_type, []),
26
+ utility_code=dataclass_loader_utilitycode,
27
+ args=[],
28
+ )
29
+
30
+ def make_dataclass_call_helper(pos, callable, kwds):
31
+ utility_code = UtilityCode.load_cached("DataclassesCallHelper", "Dataclasses.c")
32
+ func_type = PyrexTypes.CFuncType(
33
+ PyrexTypes.py_object_type, [
34
+ PyrexTypes.CFuncTypeArg("callable", PyrexTypes.py_object_type, None),
35
+ PyrexTypes.CFuncTypeArg("kwds", PyrexTypes.py_object_type, None)
36
+ ],
37
+ )
38
+ return ExprNodes.PythonCapiCallNode(
39
+ pos,
40
+ function_name="__Pyx_DataclassesCallHelper",
41
+ func_type=func_type,
42
+ utility_code=utility_code,
43
+ args=[callable, kwds],
44
+ )
45
+
46
+
47
+ class RemoveAssignmentsToNames(VisitorTransform, SkipDeclarations):
48
+ """
49
+ Cython (and Python) normally treats
50
+
51
+ class A:
52
+ x = 1
53
+
54
+ as generating a class attribute. However for dataclasses the `= 1` should be interpreted as
55
+ a default value to initialize an instance attribute with.
56
+ This transform therefore removes the `x=1` assignment so that the class attribute isn't
57
+ generated, while recording what it has removed so that it can be used in the initialization.
58
+ """
59
+ def __init__(self, names):
60
+ super().__init__()
61
+ self.names = names
62
+ self.removed_assignments = {}
63
+
64
+ def visit_CClassNode(self, node):
65
+ self.visitchildren(node)
66
+ return node
67
+
68
+ def visit_PyClassNode(self, node):
69
+ return node # go no further
70
+
71
+ def visit_FuncDefNode(self, node):
72
+ return node # go no further
73
+
74
+ def visit_SingleAssignmentNode(self, node):
75
+ if node.lhs.is_name and node.lhs.name in self.names:
76
+ if node.lhs.name in self.removed_assignments:
77
+ warning(node.pos, ("Multiple assignments for '%s' in dataclass; "
78
+ "using most recent") % node.lhs.name, 1)
79
+ self.removed_assignments[node.lhs.name] = node.rhs
80
+ return []
81
+ return node
82
+
83
+ # I believe cascaded assignment is always a syntax error with annotations
84
+ # so there's no need to define visit_CascadedAssignmentNode
85
+
86
+ def visit_Node(self, node):
87
+ self.visitchildren(node)
88
+ return node
89
+
90
+
91
+ class TemplateCode:
92
+ """
93
+ Adds the ability to keep track of placeholder argument names to PyxCodeWriter.
94
+
95
+ Also adds extra_stats which are nodes bundled at the end when this
96
+ is converted to a tree.
97
+ """
98
+ _placeholder_count = 0
99
+
100
+ def __init__(self, writer=None, placeholders=None, extra_stats=None):
101
+ self.writer = PyxCodeWriter() if writer is None else writer
102
+ self.placeholders = {} if placeholders is None else placeholders
103
+ self.extra_stats = [] if extra_stats is None else extra_stats
104
+
105
+ def add_code_line(self, code_line):
106
+ self.writer.putln(code_line)
107
+
108
+ def add_code_chunk(self, code_chunk):
109
+ self.writer.put_chunk(code_chunk)
110
+
111
+ def reset(self):
112
+ # don't attempt to reset placeholders - it really doesn't matter if
113
+ # we have unused placeholders
114
+ self.writer.reset()
115
+
116
+ def empty(self):
117
+ return self.writer.empty()
118
+
119
+ def indent(self):
120
+ self.writer.indent()
121
+
122
+ def dedent(self):
123
+ self.writer.dedent()
124
+
125
+ def indenter(self, block_opener_line):
126
+ return self.writer.indenter(block_opener_line)
127
+
128
+ def new_placeholder(self, field_names, value):
129
+ name = self._new_placeholder_name(field_names)
130
+ self.placeholders[name] = value
131
+ return name
132
+
133
+ def add_extra_statements(self, statements):
134
+ if self.extra_stats is None:
135
+ assert False, "Can only use add_extra_statements on top-level writer"
136
+ self.extra_stats.extend(statements)
137
+
138
+ def _new_placeholder_name(self, field_names):
139
+ while True:
140
+ name = f"DATACLASS_PLACEHOLDER_{self._placeholder_count:d}"
141
+ if (name not in self.placeholders
142
+ and name not in field_names):
143
+ # make sure name isn't already used and doesn't
144
+ # conflict with a variable name (which is unlikely but possible)
145
+ break
146
+ self._placeholder_count += 1
147
+ return name
148
+
149
+ def generate_tree(self, level='c_class'):
150
+ stat_list_node = TreeFragment(
151
+ self.writer.getvalue(),
152
+ level=level,
153
+ pipeline=[NormalizeTree(None)],
154
+ ).substitute(self.placeholders)
155
+
156
+ stat_list_node = InterpretCompilerDirectives(None, {})(stat_list_node)
157
+
158
+ stat_list_node.stats += self.extra_stats
159
+ return stat_list_node
160
+
161
+ def insertion_point(self):
162
+ new_writer = self.writer.insertion_point()
163
+ return TemplateCode(
164
+ writer=new_writer,
165
+ placeholders=self.placeholders,
166
+ extra_stats=self.extra_stats,
167
+ )
168
+
169
+
170
+ class _MISSING_TYPE:
171
+ pass
172
+ MISSING = _MISSING_TYPE()
173
+
174
+
175
+ class Field:
176
+ """
177
+ Field is based on the dataclasses.field class from the standard library module.
178
+ It is used internally during the generation of Cython dataclasses to keep track
179
+ of the settings for individual attributes.
180
+
181
+ Attributes of this class are stored as nodes so they can be used in code construction
182
+ more readily (i.e. we store BoolNode rather than bool)
183
+ """
184
+ default = MISSING
185
+ default_factory = MISSING
186
+ private = False
187
+
188
+ literal_keys = ("repr", "hash", "init", "compare", "metadata")
189
+
190
+ # default values are defined by the CPython dataclasses.field
191
+ def __init__(self, pos, default=MISSING, default_factory=MISSING,
192
+ repr=None, hash=None, init=None,
193
+ compare=None, metadata=None,
194
+ is_initvar=False, is_classvar=False,
195
+ **additional_kwds):
196
+ if default is not MISSING:
197
+ self.default = default
198
+ if default_factory is not MISSING:
199
+ self.default_factory = default_factory
200
+ self.repr = repr or ExprNodes.BoolNode(pos, value=True)
201
+ self.hash = hash or ExprNodes.NoneNode(pos)
202
+ self.init = init or ExprNodes.BoolNode(pos, value=True)
203
+ self.compare = compare or ExprNodes.BoolNode(pos, value=True)
204
+ self.metadata = metadata or ExprNodes.NoneNode(pos)
205
+ self.is_initvar = is_initvar
206
+ self.is_classvar = is_classvar
207
+
208
+ for k, v in additional_kwds.items():
209
+ # There should not be any additional keywords!
210
+ error(v.pos, "cython.dataclasses.field() got an unexpected keyword argument '%s'" % k)
211
+
212
+ for field_name in self.literal_keys:
213
+ field_value = getattr(self, field_name)
214
+ if not field_value.is_literal:
215
+ error(field_value.pos,
216
+ "cython.dataclasses.field parameter '%s' must be a literal value" % field_name)
217
+
218
+ def iterate_record_node_arguments(self):
219
+ for key in (self.literal_keys + ('default', 'default_factory')):
220
+ value = getattr(self, key)
221
+ if value is not MISSING:
222
+ yield key, value
223
+
224
+
225
+ def process_class_get_fields(node):
226
+ var_entries = node.scope.var_entries
227
+ # order of definition is used in the dataclass
228
+ var_entries = sorted(var_entries, key=operator.attrgetter('pos'))
229
+ var_names = [entry.name for entry in var_entries]
230
+
231
+ # don't treat `x = 1` as an assignment of a class attribute within the dataclass
232
+ transform = RemoveAssignmentsToNames(var_names)
233
+ transform(node)
234
+ default_value_assignments = transform.removed_assignments
235
+
236
+ base_type = node.base_type
237
+ fields = OrderedDict()
238
+ while base_type:
239
+ if base_type.is_external or not base_type.scope.implemented:
240
+ warning(node.pos, "Cannot reliably handle Cython dataclasses with base types "
241
+ "in external modules since it is not possible to tell what fields they have", 2)
242
+ if base_type.dataclass_fields:
243
+ fields = base_type.dataclass_fields.copy()
244
+ break
245
+ base_type = base_type.base_type
246
+
247
+ for entry in var_entries:
248
+ name = entry.name
249
+ is_initvar = entry.declared_with_pytyping_modifier("dataclasses.InitVar")
250
+ # TODO - classvars aren't included in "var_entries" so are missed here
251
+ # and thus this code is never triggered
252
+ is_classvar = entry.declared_with_pytyping_modifier("typing.ClassVar")
253
+ if name in default_value_assignments:
254
+ assignment = default_value_assignments[name]
255
+ if (isinstance(assignment, ExprNodes.CallNode) and (
256
+ assignment.function.as_cython_attribute() == "dataclasses.field" or
257
+ Builtin.exprnode_to_known_standard_library_name(
258
+ assignment.function, node.scope) == "dataclasses.field")):
259
+ # I believe most of this is well-enforced when it's treated as a directive
260
+ # but it doesn't hurt to make sure
261
+ valid_general_call = (isinstance(assignment, ExprNodes.GeneralCallNode)
262
+ and isinstance(assignment.positional_args, ExprNodes.TupleNode)
263
+ and not assignment.positional_args.args
264
+ and (assignment.keyword_args is None or isinstance(assignment.keyword_args, ExprNodes.DictNode)))
265
+ valid_simple_call = (isinstance(assignment, ExprNodes.SimpleCallNode) and not assignment.args)
266
+ if not (valid_general_call or valid_simple_call):
267
+ error(assignment.pos, "Call to 'cython.dataclasses.field' must only consist "
268
+ "of compile-time keyword arguments")
269
+ continue
270
+ keyword_args = assignment.keyword_args.as_python_dict() if valid_general_call and assignment.keyword_args else {}
271
+ if 'default' in keyword_args and 'default_factory' in keyword_args:
272
+ error(assignment.pos, "cannot specify both default and default_factory")
273
+ continue
274
+ field = Field(node.pos, **keyword_args)
275
+ else:
276
+ if assignment.type in [Builtin.list_type, Builtin.dict_type, Builtin.set_type]:
277
+ # The standard library module generates a TypeError at runtime
278
+ # in this situation.
279
+ # Error message is copied from CPython
280
+ error(assignment.pos, "mutable default <class '{}'> for field {} is not allowed: "
281
+ "use default_factory".format(assignment.type.name, name))
282
+
283
+ field = Field(node.pos, default=assignment)
284
+ else:
285
+ field = Field(node.pos)
286
+ field.is_initvar = is_initvar
287
+ field.is_classvar = is_classvar
288
+ if entry.visibility == "private":
289
+ field.private = True
290
+ fields[name] = field
291
+ node.entry.type.dataclass_fields = fields
292
+ return fields
293
+
294
+
295
+ def handle_cclass_dataclass(node, dataclass_args, analyse_decs_transform):
296
+ # default argument values from https://docs.python.org/3/library/dataclasses.html
297
+ kwargs = dict(init=True, repr=True, eq=True,
298
+ order=False, unsafe_hash=False,
299
+ frozen=False, kw_only=False, match_args=True)
300
+ if dataclass_args is not None:
301
+ if dataclass_args[0]:
302
+ error(node.pos, "cython.dataclasses.dataclass takes no positional arguments")
303
+ for k, v in dataclass_args[1].items():
304
+ if k in kwargs and isinstance(v, ExprNodes.BoolNode):
305
+ kwargs[k] = v.value
306
+ continue
307
+
308
+ if k not in kwargs:
309
+ error(node.pos,
310
+ "cython.dataclasses.dataclass() got an unexpected keyword argument '%s'" % k)
311
+ if not isinstance(v, ExprNodes.BoolNode):
312
+ error(node.pos,
313
+ "Arguments passed to cython.dataclasses.dataclass must be True or False")
314
+
315
+ kw_only = kwargs['kw_only']
316
+
317
+ fields = process_class_get_fields(node)
318
+
319
+ dataclass_module = make_dataclasses_module_callnode(node.pos)
320
+
321
+ # create __dataclass_params__ attribute. I try to use the exact
322
+ # `_DataclassParams` class defined in the standard library module if at all possible
323
+ # for maximum duck-typing compatibility.
324
+ dataclass_params_func = ExprNodes.AttributeNode(node.pos, obj=dataclass_module,
325
+ attribute=EncodedString("_DataclassParams"))
326
+ dataclass_params_keywords = ExprNodes.DictNode.from_pairs(
327
+ node.pos,
328
+ [ (ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(k)),
329
+ ExprNodes.BoolNode(node.pos, value=v, type=Builtin.bool_type))
330
+ for k, v in kwargs.items() ] +
331
+ [ (ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(k)),
332
+ ExprNodes.BoolNode(node.pos, value=v, type=Builtin.bool_type))
333
+ for k, v in [('kw_only', kw_only),
334
+ ('slots', False), ('weakref_slot', False)]
335
+ ])
336
+ dataclass_params = make_dataclass_call_helper(
337
+ node.pos, dataclass_params_func, dataclass_params_keywords)
338
+ dataclass_params_assignment = Nodes.SingleAssignmentNode(
339
+ node.pos,
340
+ lhs = ExprNodes.NameNode(node.pos, name=EncodedString("__dataclass_params__")),
341
+ rhs = dataclass_params)
342
+
343
+ dataclass_fields_stats = _set_up_dataclass_fields(node, fields, dataclass_module)
344
+
345
+ stats = Nodes.StatListNode(node.pos,
346
+ stats=[dataclass_params_assignment] + dataclass_fields_stats)
347
+
348
+ critical_section_substitution = ExprNodes.NameNode(
349
+ node.pos,
350
+ name="critical_section",
351
+ cython_attribute="critical_section"
352
+ )
353
+
354
+ code = TemplateCode()
355
+ critical_section_placeholder_name = code.new_placeholder(
356
+ fields,
357
+ critical_section_substitution
358
+ )
359
+ generate_init_code(code, kwargs['init'], node, fields, kw_only,
360
+ critical_section_placeholder_name=critical_section_placeholder_name)
361
+ generate_match_args(code, kwargs['match_args'], node, fields, kw_only)
362
+ generate_repr_code(code, kwargs['repr'], node, fields,
363
+ critical_section_placeholder_name=critical_section_placeholder_name)
364
+ generate_eq_code(code, kwargs['eq'], node, fields,
365
+ critical_section_placeholder_name=critical_section_placeholder_name)
366
+ generate_order_code(code, kwargs['order'], node, fields,
367
+ critical_section_placeholder_name=critical_section_placeholder_name)
368
+ generate_hash_code(code, kwargs['unsafe_hash'], kwargs['eq'], kwargs['frozen'], node, fields,
369
+ critical_section_placeholder_name=critical_section_placeholder_name)
370
+
371
+ stats.stats += code.generate_tree().stats
372
+
373
+ # turn off annotation typing, so all arguments to __init__ are accepted as
374
+ # generic objects and thus can accept _HAS_DEFAULT_FACTORY.
375
+ # Type conversion comes later
376
+ comp_directives = Nodes.CompilerDirectivesNode(node.pos,
377
+ directives=copy_inherited_directives(node.scope.directives, annotation_typing=False),
378
+ body=stats)
379
+
380
+ comp_directives.analyse_declarations(node.scope)
381
+ # probably already in this scope, but it doesn't hurt to make sure
382
+ analyse_decs_transform.enter_scope(node, node.scope)
383
+ analyse_decs_transform.visit(comp_directives)
384
+ analyse_decs_transform.exit_scope()
385
+
386
+ node.body.stats.append(comp_directives)
387
+
388
+
389
+ def generate_init_code(code, init, node, fields, kw_only, *, critical_section_placeholder_name):
390
+ """
391
+ Notes on CPython generated "__init__":
392
+ * Implemented in `_init_fn`.
393
+ * The use of the `dataclasses._HAS_DEFAULT_FACTORY` sentinel value as
394
+ the default argument for fields that need constructing with a factory
395
+ function is copied from the CPython implementation. (`None` isn't
396
+ suitable because it could also be a value for the user to pass.)
397
+ There's no real reason why it needs importing from the dataclasses module
398
+ though - it could equally be a value generated by Cython when the module loads.
399
+ * seen_default and the associated error message are copied directly from Python
400
+ * Call to user-defined __post_init__ function (if it exists) is copied from
401
+ CPython.
402
+
403
+ Cython behaviour deviates a little here (to be decided if this is right...)
404
+ Because the class variable from the assignment does not exist Cython fields will
405
+ return None (or whatever their type default is) if not initialized while Python
406
+ dataclasses will fall back to looking up the class variable.
407
+ """
408
+ if not init or node.scope.lookup_here("__init__"):
409
+ return
410
+
411
+ # selfname behaviour copied from the cpython module
412
+ selfname = "__dataclass_self__" if "self" in fields else "self"
413
+ args = [selfname]
414
+
415
+ if kw_only:
416
+ args.append("*")
417
+
418
+ function_start_point = code.insertion_point()
419
+ code = code.insertion_point()
420
+ code.indent()
421
+ code.indent() # second indent is for "with critical_section" block
422
+
423
+ # create a temp to get _HAS_DEFAULT_FACTORY
424
+ dataclass_module = make_dataclasses_module_callnode(node.pos)
425
+ has_default_factory = ExprNodes.AttributeNode(
426
+ node.pos,
427
+ obj=dataclass_module,
428
+ attribute=EncodedString("_HAS_DEFAULT_FACTORY")
429
+ )
430
+
431
+ default_factory_placeholder = code.new_placeholder(fields, has_default_factory)
432
+
433
+ seen_default = False
434
+ for name, field in fields.items():
435
+ entry = node.scope.lookup(name)
436
+ if entry.annotation:
437
+ annotation = f": {entry.annotation.string.value}"
438
+ else:
439
+ annotation = ""
440
+ assignment = ''
441
+ if field.default is not MISSING or field.default_factory is not MISSING:
442
+ if field.init.value:
443
+ seen_default = True
444
+ if field.default_factory is not MISSING:
445
+ ph_name = default_factory_placeholder
446
+ else:
447
+ ph_name = code.new_placeholder(fields, field.default) # 'default' should be a node
448
+ assignment = f" = {ph_name}"
449
+ elif seen_default and not kw_only and field.init.value:
450
+ error(entry.pos, ("non-default argument '%s' follows default argument "
451
+ "in dataclass __init__") % name)
452
+ code.reset()
453
+ return
454
+
455
+ if field.init.value:
456
+ args.append(f"{name}{annotation}{assignment}")
457
+
458
+ if field.is_initvar:
459
+ continue
460
+ elif field.default_factory is MISSING:
461
+ if field.init.value:
462
+ code.add_code_line(f"{selfname}.{name} = {name}")
463
+ elif assignment:
464
+ # not an argument to the function, but is still initialized
465
+ code.add_code_line(f"{selfname}.{name}{assignment}")
466
+ else:
467
+ ph_name = code.new_placeholder(fields, field.default_factory)
468
+ if field.init.value:
469
+ # close to:
470
+ # def __init__(self, name=_PLACEHOLDER_VALUE):
471
+ # self.name = name_default_factory() if name is _PLACEHOLDER_VALUE else name
472
+ code.add_code_line(
473
+ f"{selfname}.{name} = {ph_name}() if {name} is {default_factory_placeholder} else {name}"
474
+ )
475
+ else:
476
+ # still need to use the default factory to initialize
477
+ code.add_code_line(f"{selfname}.{name} = {ph_name}()")
478
+
479
+ if node.scope.lookup("__post_init__"):
480
+ post_init_vars = ", ".join(name for name, field in fields.items()
481
+ if field.is_initvar)
482
+ code.add_code_line(f"{selfname}.__post_init__({post_init_vars})")
483
+
484
+ if code.empty():
485
+ code.add_code_line("pass")
486
+
487
+ args = ", ".join(args)
488
+ function_start_point.add_code_line(f"def __init__({args}):")
489
+ function_start_point.indent()
490
+ # Although __init__ is usually called on the only reference to self, it doesn't
491
+ # have to be.
492
+ function_start_point.add_code_line(f"with {critical_section_placeholder_name}({selfname}):")
493
+
494
+
495
+ def generate_match_args(code, match_args, node, fields, global_kw_only):
496
+ """
497
+ Generates a tuple containing what would be the positional args to __init__
498
+
499
+ Note that this is generated even if the user overrides init
500
+ """
501
+ if not match_args or node.scope.lookup_here("__match_args__"):
502
+ return
503
+ positional_arg_names = []
504
+ for field_name, field in fields.items():
505
+ # TODO hasattr and global_kw_only can be removed once full kw_only support is added
506
+ field_is_kw_only = global_kw_only or (
507
+ hasattr(field, 'kw_only') and field.kw_only.value
508
+ )
509
+ if not field_is_kw_only:
510
+ positional_arg_names.append(field_name)
511
+ code.add_code_line("__match_args__ = %s" % str(tuple(positional_arg_names)))
512
+
513
+
514
+ def generate_repr_code(code, repr, node, fields, *, critical_section_placeholder_name):
515
+ """
516
+ The core of the CPython implementation is just:
517
+ ['return self.__class__.__qualname__ + f"(' +
518
+ ', '.join([f"{f.name}={{self.{f.name}!r}}"
519
+ for f in fields]) +
520
+ ')"'],
521
+
522
+ The only notable difference here is self.__class__.__qualname__ -> type(self).__name__
523
+ which is because Cython currently supports Python 2.
524
+
525
+ However, it also has some guards for recursive repr invocations. In the standard
526
+ library implementation they're done with a wrapper decorator that captures a set
527
+ (with the set keyed by id and thread). Here we create a set as a thread local
528
+ variable and key only by id.
529
+ """
530
+ if not repr or node.scope.lookup("__repr__"):
531
+ return
532
+
533
+ # The recursive guard is likely a little costly, so skip it if possible.
534
+ # is_gc_simple defines where it can contain recursive objects
535
+ needs_recursive_guard = False
536
+ for name in fields.keys():
537
+ entry = node.scope.lookup(name)
538
+ type_ = entry.type
539
+ if type_.is_memoryviewslice:
540
+ type_ = type_.dtype
541
+ if not type_.is_pyobject:
542
+ continue # no GC
543
+ if not type_.is_gc_simple:
544
+ needs_recursive_guard = True
545
+ break
546
+
547
+ if needs_recursive_guard:
548
+ code.add_code_chunk("""
549
+ __pyx_recursive_repr_guard = __import__('threading').local()
550
+ __pyx_recursive_repr_guard.running = set()
551
+ """)
552
+
553
+ with code.indenter("def __repr__(self):"):
554
+ if needs_recursive_guard:
555
+ code.add_code_chunk("""
556
+ key = id(self)
557
+ guard_set = self.__pyx_recursive_repr_guard.running
558
+ if key in guard_set: return '...'
559
+ guard_set.add(key)
560
+ try:
561
+ """)
562
+ code.indent()
563
+ code.add_code_line('name = getattr(type(self), "__qualname__", None) or type(self).__name__')
564
+ with code.indenter(f"with {critical_section_placeholder_name}(self):"):
565
+ strs = ["%s={self.%s!r}" % (name, name)
566
+ for name, field in fields.items()
567
+ if field.repr.value and not field.is_initvar]
568
+ format_string = ", ".join(strs)
569
+
570
+ code.add_code_line(f"return f'{{name}}({format_string})'")
571
+ if needs_recursive_guard:
572
+ code.dedent()
573
+ with code.indenter("finally:"):
574
+ code.add_code_line("guard_set.remove(key)")
575
+
576
+
577
+ def generate_cmp_code(code, op, funcname, node, fields, *, critical_section_placeholder_name):
578
+ if node.scope.lookup_here(funcname):
579
+ return
580
+
581
+ names = [name for name, field in fields.items() if (field.compare.value and not field.is_initvar)]
582
+
583
+ with code.indenter(f"def {funcname}(self, other):"):
584
+ code.add_code_line(f"cdef {node.class_name} other_cast")
585
+ code.add_code_chunk(f"""
586
+ if other.__class__ is not self.__class__: return NotImplemented
587
+
588
+ other_cast = <{node.class_name}>other
589
+ """)
590
+ with code.indenter(f"with {critical_section_placeholder_name}(self, other):"):
591
+ # The Python implementation of dataclasses.py does a tuple comparison
592
+ # (roughly):
593
+ # return self._attributes_to_tuple() {op} other._attributes_to_tuple()
594
+ #
595
+ # For the Cython implementation a tuple comparison isn't an option because
596
+ # not all attributes can be converted to Python objects and stored in a tuple
597
+ #
598
+ # TODO - better diagnostics of whether the types support comparison before
599
+ # generating the code. Plus, do we want to convert C structs to dicts and
600
+ # compare them that way (I think not, but it might be in demand)?
601
+ op_without_equals = op.replace('=', '')
602
+
603
+ for name in names:
604
+ if op != '==':
605
+ # tuple comparison rules - early elements take precedence
606
+ code.add_code_line(f"if self.{name} {op_without_equals} other_cast.{name}: return True")
607
+ code.add_code_line(f"if self.{name} != other_cast.{name}: return False")
608
+ code.add_code_line(f"return {'True' if '=' in op else 'False'}") # "() == ()" is True
609
+
610
+
611
+ def generate_eq_code(code, eq, node, fields, *, critical_section_placeholder_name):
612
+ if not eq:
613
+ return
614
+ generate_cmp_code(
615
+ code, "==", "__eq__", node, fields,
616
+ critical_section_placeholder_name=critical_section_placeholder_name
617
+ )
618
+
619
+
620
+ def generate_order_code(code, order, node, fields, *, critical_section_placeholder_name):
621
+ if not order:
622
+ return
623
+
624
+ for op, name in [("<", "__lt__"),
625
+ ("<=", "__le__"),
626
+ (">", "__gt__"),
627
+ (">=", "__ge__")]:
628
+ generate_cmp_code(
629
+ code, op, name, node, fields,
630
+ critical_section_placeholder_name=critical_section_placeholder_name
631
+ )
632
+
633
+
634
+ def generate_hash_code(code, unsafe_hash, eq, frozen, node, fields, *, critical_section_placeholder_name):
635
+ """
636
+ Copied from CPython implementation - the intention is to follow this as far as
637
+ is possible:
638
+ # +------------------- unsafe_hash= parameter
639
+ # | +----------- eq= parameter
640
+ # | | +--- frozen= parameter
641
+ # | | |
642
+ # v v v | | |
643
+ # | no | yes | <--- class has explicitly defined __hash__
644
+ # +=======+=======+=======+========+========+
645
+ # | False | False | False | | | No __eq__, use the base class __hash__
646
+ # +-------+-------+-------+--------+--------+
647
+ # | False | False | True | | | No __eq__, use the base class __hash__
648
+ # +-------+-------+-------+--------+--------+
649
+ # | False | True | False | None | | <-- the default, not hashable
650
+ # +-------+-------+-------+--------+--------+
651
+ # | False | True | True | add | | Frozen, so hashable, allows override
652
+ # +-------+-------+-------+--------+--------+
653
+ # | True | False | False | add | raise | Has no __eq__, but hashable
654
+ # +-------+-------+-------+--------+--------+
655
+ # | True | False | True | add | raise | Has no __eq__, but hashable
656
+ # +-------+-------+-------+--------+--------+
657
+ # | True | True | False | add | raise | Not frozen, but hashable
658
+ # +-------+-------+-------+--------+--------+
659
+ # | True | True | True | add | raise | Frozen, so hashable
660
+ # +=======+=======+=======+========+========+
661
+ # For boxes that are blank, __hash__ is untouched and therefore
662
+ # inherited from the base class. If the base is object, then
663
+ # id-based hashing is used.
664
+
665
+ The Python implementation creates a tuple of all the fields, then hashes them.
666
+ This implementation creates a tuple of all the hashes of all the fields and hashes that.
667
+ The reason for this slight difference is to avoid to-Python conversions for anything
668
+ that Cython knows how to hash directly (It doesn't look like this currently applies to
669
+ anything though...).
670
+ """
671
+
672
+ hash_entry = node.scope.lookup_here("__hash__")
673
+ if hash_entry:
674
+ # TODO ideally assignment of __hash__ to None shouldn't trigger this
675
+ # but difficult to get the right information here
676
+ if unsafe_hash:
677
+ # error message taken from CPython dataclasses module
678
+ error(node.pos, "Cannot overwrite attribute __hash__ in class %s" % node.class_name)
679
+ return
680
+
681
+ if not unsafe_hash:
682
+ if not eq:
683
+ return
684
+ if not frozen:
685
+ code.add_extra_statements([
686
+ Nodes.SingleAssignmentNode(
687
+ node.pos,
688
+ lhs=ExprNodes.NameNode(node.pos, name=EncodedString("__hash__")),
689
+ rhs=ExprNodes.NoneNode(node.pos),
690
+ )
691
+ ])
692
+ return
693
+
694
+ names = [
695
+ name for name, field in fields.items()
696
+ if not field.is_initvar and (
697
+ field.compare.value if field.hash.value is None else field.hash.value)
698
+ ]
699
+
700
+ # make a tuple of the hashes
701
+ hash_tuple_items = ", ".join("self.%s" % name for name in names)
702
+ if hash_tuple_items:
703
+ hash_tuple_items += "," # ensure that one arg form is a tuple
704
+
705
+ # if we're here we want to generate a hash
706
+ with code.indenter("def __hash__(self):"):
707
+ with code.indenter(f"with {critical_section_placeholder_name}(self):"):
708
+ code.add_code_line(f"return hash(({hash_tuple_items}))")
709
+
710
+
711
+ def get_field_type(pos, entry):
712
+ """
713
+ sets the .type attribute for a field
714
+
715
+ Returns the annotation if possible (since this is what the dataclasses
716
+ module does). If not (for example, attributes defined with cdef) then
717
+ it creates a string fallback.
718
+ """
719
+ if entry.annotation:
720
+ # Right now it doesn't look like cdef classes generate an
721
+ # __annotations__ dict, therefore it's safe to just return
722
+ # entry.annotation
723
+ # (TODO: remove .string if we ditch PEP563)
724
+ return entry.annotation.string
725
+ # If they do in future then we may need to look up into that
726
+ # to duplicating the node. The code below should do this:
727
+ #class_name_node = ExprNodes.NameNode(pos, name=entry.scope.name)
728
+ #annotations = ExprNodes.AttributeNode(
729
+ # pos, obj=class_name_node,
730
+ # attribute=EncodedString("__annotations__")
731
+ #)
732
+ #return ExprNodes.IndexNode(
733
+ # pos, base=annotations,
734
+ # index=ExprNodes.UnicodeNode(pos, value=entry.name)
735
+ #)
736
+ else:
737
+ # it's slightly unclear what the best option is here - we could
738
+ # try to return PyType_Type. This case should only happen with
739
+ # attributes defined with cdef so Cython is free to make it's own
740
+ # decision
741
+ s = EncodedString(entry.type.declaration_code("", for_display=1))
742
+ return ExprNodes.UnicodeNode(pos, value=s)
743
+
744
+
745
+ class FieldRecordNode(ExprNodes.ExprNode):
746
+ """
747
+ __dataclass_fields__ contains a bunch of field objects recording how each field
748
+ of the dataclass was initialized (mainly corresponding to the arguments passed to
749
+ the "field" function). This node is used for the attributes of these field objects.
750
+
751
+ If possible, coerces `arg` to a Python object.
752
+ Otherwise, generates a sensible backup string.
753
+ """
754
+ subexprs = ['arg']
755
+
756
+ def __init__(self, pos, arg):
757
+ super().__init__(pos, arg=arg)
758
+
759
+ def analyse_types(self, env):
760
+ self.arg.analyse_types(env)
761
+ self.type = self.arg.type
762
+ return self
763
+
764
+ def coerce_to_pyobject(self, env):
765
+ if self.arg.type.can_coerce_to_pyobject(env):
766
+ return self.arg.coerce_to_pyobject(env)
767
+ else:
768
+ # A string representation of the code that gave the field seems like a reasonable
769
+ # fallback. This'll mostly happen for "default" and "default_factory" where the
770
+ # type may be a C-type that can't be converted to Python.
771
+ return self._make_string()
772
+
773
+ def _make_string(self):
774
+ from .AutoDocTransforms import AnnotationWriter
775
+ writer = AnnotationWriter(description="Dataclass field")
776
+ string = writer.write(self.arg)
777
+ return ExprNodes.UnicodeNode(self.pos, value=EncodedString(string))
778
+
779
+ def generate_evaluation_code(self, code):
780
+ return self.arg.generate_evaluation_code(code)
781
+
782
+
783
+ def _set_up_dataclass_fields(node, fields, dataclass_module):
784
+ # For defaults and default_factories containing things like lambda,
785
+ # they're already declared in the class scope, and it creates a big
786
+ # problem if multiple copies are floating around in both the __init__
787
+ # function, and in the __dataclass_fields__ structure.
788
+ # Therefore, create module-level constants holding these values and
789
+ # pass those around instead
790
+ #
791
+ # If possible we use the `Field` class defined in the standard library
792
+ # module so that the information stored here is as close to a regular
793
+ # dataclass as is possible.
794
+ variables_assignment_stats = []
795
+ for name, field in fields.items():
796
+ if field.private:
797
+ continue # doesn't appear in the public interface
798
+ for attrname in [ "default", "default_factory" ]:
799
+ field_default = getattr(field, attrname)
800
+ if field_default is MISSING or field_default.is_literal or field_default.is_name:
801
+ # some simple cases where we don't need to set up
802
+ # the variable as a module-level constant
803
+ continue
804
+ global_scope = node.scope.global_scope()
805
+ module_field_name = global_scope.mangle(
806
+ global_scope.mangle(Naming.dataclass_field_default_cname, node.class_name),
807
+ name)
808
+ # create an entry in the global scope for this variable to live
809
+ field_node = ExprNodes.NameNode(field_default.pos, name=EncodedString(module_field_name))
810
+ field_node.entry = global_scope.declare_var(
811
+ field_node.name, type=field_default.type or PyrexTypes.unspecified_type,
812
+ pos=field_default.pos, cname=field_node.name, is_cdef=True,
813
+ # TODO: do we need to set 'pytyping_modifiers' here?
814
+ )
815
+ # replace the field so that future users just receive the namenode
816
+ setattr(field, attrname, field_node)
817
+
818
+ variables_assignment_stats.append(
819
+ Nodes.SingleAssignmentNode(field_default.pos, lhs=field_node, rhs=field_default))
820
+
821
+ placeholders = {}
822
+ field_func = ExprNodes.AttributeNode(node.pos, obj=dataclass_module,
823
+ attribute=EncodedString("field"))
824
+ dc_fields = ExprNodes.DictNode(node.pos, key_value_pairs=[])
825
+ dc_fields_namevalue_assignments = []
826
+
827
+ for name, field in fields.items():
828
+ if field.private:
829
+ continue # doesn't appear in the public interface
830
+ type_placeholder_name = "PLACEHOLDER_%s" % name
831
+ placeholders[type_placeholder_name] = get_field_type(
832
+ node.pos, node.scope.entries[name]
833
+ )
834
+
835
+ # defining these make the fields introspect more like a Python dataclass
836
+ field_type_placeholder_name = "PLACEHOLDER_FIELD_TYPE_%s" % name
837
+ if field.is_initvar:
838
+ placeholders[field_type_placeholder_name] = ExprNodes.AttributeNode(
839
+ node.pos, obj=dataclass_module,
840
+ attribute=EncodedString("_FIELD_INITVAR")
841
+ )
842
+ elif field.is_classvar:
843
+ # TODO - currently this isn't triggered
844
+ placeholders[field_type_placeholder_name] = ExprNodes.AttributeNode(
845
+ node.pos, obj=dataclass_module,
846
+ attribute=EncodedString("_FIELD_CLASSVAR")
847
+ )
848
+ else:
849
+ placeholders[field_type_placeholder_name] = ExprNodes.AttributeNode(
850
+ node.pos, obj=dataclass_module,
851
+ attribute=EncodedString("_FIELD")
852
+ )
853
+
854
+ dc_field_keywords = ExprNodes.DictNode.from_pairs(
855
+ node.pos,
856
+ [(ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(k)),
857
+ FieldRecordNode(node.pos, arg=v))
858
+ for k, v in field.iterate_record_node_arguments()]
859
+
860
+ )
861
+ dc_field_call = make_dataclass_call_helper(
862
+ node.pos, field_func, dc_field_keywords
863
+ )
864
+ dc_fields.key_value_pairs.append(
865
+ ExprNodes.DictItemNode(
866
+ node.pos,
867
+ key=ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(name)),
868
+ value=dc_field_call))
869
+ dc_fields_namevalue_assignments.append(
870
+ dedent(f"""\
871
+ __dataclass_fields__[{name!r}].name = {name!r}
872
+ __dataclass_fields__[{name!r}].type = {type_placeholder_name}
873
+ __dataclass_fields__[{name!r}]._field_type = {field_type_placeholder_name}
874
+ """))
875
+
876
+ dataclass_fields_assignment = \
877
+ Nodes.SingleAssignmentNode(node.pos,
878
+ lhs = ExprNodes.NameNode(node.pos,
879
+ name=EncodedString("__dataclass_fields__")),
880
+ rhs = dc_fields)
881
+
882
+ dc_fields_namevalue_assignments = "\n".join(dc_fields_namevalue_assignments)
883
+ dc_fields_namevalue_assignments = TreeFragment(dc_fields_namevalue_assignments,
884
+ level="c_class",
885
+ pipeline=[NormalizeTree(None)])
886
+ dc_fields_namevalue_assignments = dc_fields_namevalue_assignments.substitute(placeholders)
887
+
888
+ return (variables_assignment_stats
889
+ + [dataclass_fields_assignment]
890
+ + dc_fields_namevalue_assignments.stats)