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