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