koichi12 commited on
Commit
85f39ef
·
verified ·
1 Parent(s): c469bd7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/AnalysedTreeTransforms.py +99 -0
  2. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Builtin.py +644 -0
  3. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Code.pxd +131 -0
  4. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/CodeGeneration.py +35 -0
  5. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Future.py +16 -0
  6. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Interpreter.py +64 -0
  7. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Lexicon.py +342 -0
  8. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/MemoryView.py +863 -0
  9. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/ModuleNode.py +0 -0
  10. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Nodes.py +0 -0
  11. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Options.py +799 -0
  12. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/ParseTreeTransforms.py +0 -0
  13. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/PyrexTypes.py +0 -0
  14. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Pythran.py +227 -0
  15. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Scanning.py +582 -0
  16. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Symtab.py +0 -0
  17. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/TreeFragment.py +280 -0
  18. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/TypeInference.py +596 -0
  19. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Visitor.pxd +55 -0
  20. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Buffer.cpython-311.pyc +0 -0
  21. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/FusedNode.cpython-311.pyc +0 -0
  22. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Future.cpython-311.pyc +0 -0
  23. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Main.cpython-311.pyc +0 -0
  24. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/MemoryView.cpython-311.pyc +0 -0
  25. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/TreeFragment.cpython-311.pyc +0 -0
  26. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/TypeInference.cpython-311.pyc +0 -0
  27. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/UtilNodes.cpython-311.pyc +0 -0
  28. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Visitor.cpython-311.pyc +0 -0
  29. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/Lexicons.py +179 -0
  30. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/DFA.cpython-311.pyc +0 -0
  31. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/Machines.cpython-311.pyc +0 -0
  32. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/Scanners.cpython-311.pyc +0 -0
  33. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Builtins.c +609 -0
  34. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/CommonStructures.c +139 -0
  35. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Coroutine.c +0 -0
  36. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/CppConvert.pyx +273 -0
  37. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/ExtensionTypes.c +660 -0
  38. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/FunctionArguments.c +587 -0
  39. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/MemoryView.pyx +1481 -0
  40. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Profile.c +383 -0
  41. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/StringTools.c +1294 -0
  42. tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/UFuncs_C.c +42 -0
  43. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/__pycache__/__init__.cpython-311.pyc +0 -0
  44. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc +0 -0
  45. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_centrality.cpython-311.pyc +0 -0
  46. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-311.pyc +0 -0
  47. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-311.pyc +0 -0
  48. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_generators.cpython-311.pyc +0 -0
  49. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matching.cpython-311.pyc +0 -0
  50. tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matrix.cpython-311.pyc +0 -0
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/AnalysedTreeTransforms.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from .Visitor import ScopeTrackingTransform
4
+ from .Nodes import StatListNode, SingleAssignmentNode, CFuncDefNode, DefNode
5
+ from .ExprNodes import DictNode, DictItemNode, NameNode, UnicodeNode
6
+ from .PyrexTypes import py_object_type
7
+ from .StringEncoding import EncodedString
8
+ from . import Symtab
9
+
10
+ class AutoTestDictTransform(ScopeTrackingTransform):
11
+ # Handles autotestdict directive
12
+
13
+ excludelist = ['__cinit__', '__dealloc__', '__richcmp__',
14
+ '__nonzero__', '__bool__',
15
+ '__len__', '__contains__']
16
+
17
+ def visit_ModuleNode(self, node):
18
+ if node.is_pxd:
19
+ return node
20
+ self.scope_type = 'module'
21
+ self.scope_node = node
22
+
23
+ if not self.current_directives['autotestdict']:
24
+ return node
25
+ self.all_docstrings = self.current_directives['autotestdict.all']
26
+ self.cdef_docstrings = self.all_docstrings or self.current_directives['autotestdict.cdef']
27
+
28
+ assert isinstance(node.body, StatListNode)
29
+
30
+ # First see if __test__ is already created
31
+ if u'__test__' in node.scope.entries:
32
+ # Do nothing
33
+ return node
34
+
35
+ pos = node.pos
36
+
37
+ self.tests = []
38
+ self.testspos = node.pos
39
+
40
+ test_dict_entry = node.scope.declare_var(EncodedString(u'__test__'),
41
+ py_object_type,
42
+ pos,
43
+ visibility='public')
44
+ create_test_dict_assignment = SingleAssignmentNode(pos,
45
+ lhs=NameNode(pos, name=EncodedString(u'__test__'),
46
+ entry=test_dict_entry),
47
+ rhs=DictNode(pos, key_value_pairs=self.tests))
48
+ self.visitchildren(node)
49
+ node.body.stats.append(create_test_dict_assignment)
50
+ return node
51
+
52
+ def add_test(self, testpos, path, doctest):
53
+ pos = self.testspos
54
+ keystr = u'%s (line %d)' % (path, testpos[1])
55
+ key = UnicodeNode(pos, value=EncodedString(keystr))
56
+ value = UnicodeNode(pos, value=doctest)
57
+ self.tests.append(DictItemNode(pos, key=key, value=value))
58
+
59
+ def visit_ExprNode(self, node):
60
+ # expressions cannot contain functions and lambda expressions
61
+ # do not have a docstring
62
+ return node
63
+
64
+ def visit_FuncDefNode(self, node):
65
+ if not node.doc or (isinstance(node, DefNode) and node.fused_py_func):
66
+ return node
67
+ if not self.cdef_docstrings:
68
+ if isinstance(node, CFuncDefNode) and not node.py_func:
69
+ return node
70
+ if not self.all_docstrings and '>>>' not in node.doc:
71
+ return node
72
+
73
+ pos = self.testspos
74
+ if self.scope_type == 'module':
75
+ path = node.entry.name
76
+ elif self.scope_type in ('pyclass', 'cclass'):
77
+ if isinstance(node, CFuncDefNode):
78
+ if node.py_func is not None:
79
+ name = node.py_func.name
80
+ else:
81
+ name = node.entry.name
82
+ else:
83
+ name = node.name
84
+ if self.scope_type == 'cclass' and name in self.excludelist:
85
+ return node
86
+ if self.scope_type == 'pyclass':
87
+ class_name = self.scope_node.name
88
+ else:
89
+ class_name = self.scope_node.class_name
90
+ if isinstance(node.entry.scope, Symtab.PropertyScope):
91
+ property_method_name = node.entry.scope.name
92
+ path = "%s.%s.%s" % (class_name, node.entry.scope.name,
93
+ node.entry.name)
94
+ else:
95
+ path = "%s.%s" % (class_name, node.entry.name)
96
+ else:
97
+ assert False
98
+ self.add_test(node.pos, path, node.doc)
99
+ return node
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Builtin.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Builtin Definitions
3
+ #
4
+
5
+ from __future__ import absolute_import
6
+
7
+ from .StringEncoding import EncodedString
8
+ from .Symtab import BuiltinScope, StructOrUnionScope, ModuleScope, Entry
9
+ from .Code import UtilityCode, TempitaUtilityCode
10
+ from .TypeSlots import Signature
11
+ from . import PyrexTypes
12
+
13
+
14
+ # C-level implementations of builtin types, functions and methods
15
+
16
+ iter_next_utility_code = UtilityCode.load("IterNext", "ObjectHandling.c")
17
+ getattr_utility_code = UtilityCode.load("GetAttr", "ObjectHandling.c")
18
+ getattr3_utility_code = UtilityCode.load("GetAttr3", "Builtins.c")
19
+ pyexec_utility_code = UtilityCode.load("PyExec", "Builtins.c")
20
+ pyexec_globals_utility_code = UtilityCode.load("PyExecGlobals", "Builtins.c")
21
+ globals_utility_code = UtilityCode.load("Globals", "Builtins.c")
22
+
23
+ builtin_utility_code = {
24
+ 'StopAsyncIteration': UtilityCode.load_cached("StopAsyncIteration", "Coroutine.c"),
25
+ }
26
+
27
+
28
+ # mapping from builtins to their C-level equivalents
29
+
30
+ class _BuiltinOverride(object):
31
+ def __init__(self, py_name, args, ret_type, cname, py_equiv="*",
32
+ utility_code=None, sig=None, func_type=None,
33
+ is_strict_signature=False, builtin_return_type=None,
34
+ nogil=None):
35
+ self.py_name, self.cname, self.py_equiv = py_name, cname, py_equiv
36
+ self.args, self.ret_type = args, ret_type
37
+ self.func_type, self.sig = func_type, sig
38
+ self.builtin_return_type = builtin_return_type
39
+ self.is_strict_signature = is_strict_signature
40
+ self.utility_code = utility_code
41
+ self.nogil = nogil
42
+
43
+ def build_func_type(self, sig=None, self_arg=None):
44
+ if sig is None:
45
+ sig = Signature(self.args, self.ret_type, nogil=self.nogil)
46
+ sig.exception_check = False # not needed for the current builtins
47
+ func_type = sig.function_type(self_arg)
48
+ if self.is_strict_signature:
49
+ func_type.is_strict_signature = True
50
+ if self.builtin_return_type:
51
+ func_type.return_type = builtin_types[self.builtin_return_type]
52
+ return func_type
53
+
54
+
55
+ class BuiltinAttribute(object):
56
+ def __init__(self, py_name, cname=None, field_type=None, field_type_name=None):
57
+ self.py_name = py_name
58
+ self.cname = cname or py_name
59
+ self.field_type_name = field_type_name # can't do the lookup before the type is declared!
60
+ self.field_type = field_type
61
+
62
+ def declare_in_type(self, self_type):
63
+ if self.field_type_name is not None:
64
+ # lazy type lookup
65
+ field_type = builtin_scope.lookup(self.field_type_name).type
66
+ else:
67
+ field_type = self.field_type or PyrexTypes.py_object_type
68
+ entry = self_type.scope.declare(self.py_name, self.cname, field_type, None, 'private')
69
+ entry.is_variable = True
70
+
71
+
72
+ class BuiltinFunction(_BuiltinOverride):
73
+ def declare_in_scope(self, scope):
74
+ func_type, sig = self.func_type, self.sig
75
+ if func_type is None:
76
+ func_type = self.build_func_type(sig)
77
+ scope.declare_builtin_cfunction(self.py_name, func_type, self.cname,
78
+ self.py_equiv, self.utility_code)
79
+
80
+
81
+ class BuiltinMethod(_BuiltinOverride):
82
+ def declare_in_type(self, self_type):
83
+ method_type, sig = self.func_type, self.sig
84
+ if method_type is None:
85
+ # override 'self' type (first argument)
86
+ self_arg = PyrexTypes.CFuncTypeArg("", self_type, None)
87
+ self_arg.not_none = True
88
+ self_arg.accept_builtin_subtypes = True
89
+ method_type = self.build_func_type(sig, self_arg)
90
+ self_type.scope.declare_builtin_cfunction(
91
+ self.py_name, method_type, self.cname, utility_code=self.utility_code)
92
+
93
+
94
+ class BuiltinProperty(object):
95
+ # read only for now
96
+ def __init__(self, py_name, property_type, call_cname,
97
+ exception_value=None, exception_check=None, utility_code=None):
98
+ self.py_name = py_name
99
+ self.property_type = property_type
100
+ self.call_cname = call_cname
101
+ self.utility_code = utility_code
102
+ self.exception_value = exception_value
103
+ self.exception_check = exception_check
104
+
105
+ def declare_in_type(self, self_type):
106
+ self_type.scope.declare_cproperty(
107
+ self.py_name,
108
+ self.property_type,
109
+ self.call_cname,
110
+ exception_value=self.exception_value,
111
+ exception_check=self.exception_check,
112
+ utility_code=self.utility_code
113
+ )
114
+
115
+
116
+ builtin_function_table = [
117
+ # name, args, return, C API func, py equiv = "*"
118
+ BuiltinFunction('abs', "d", "d", "fabs",
119
+ is_strict_signature=True, nogil=True),
120
+ BuiltinFunction('abs', "f", "f", "fabsf",
121
+ is_strict_signature=True, nogil=True),
122
+ BuiltinFunction('abs', "i", "i", "abs",
123
+ is_strict_signature=True, nogil=True),
124
+ BuiltinFunction('abs', "l", "l", "labs",
125
+ is_strict_signature=True, nogil=True),
126
+ BuiltinFunction('abs', None, None, "__Pyx_abs_longlong",
127
+ utility_code = UtilityCode.load("abs_longlong", "Builtins.c"),
128
+ func_type = PyrexTypes.CFuncType(
129
+ PyrexTypes.c_longlong_type, [
130
+ PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_longlong_type, None)
131
+ ],
132
+ is_strict_signature = True, nogil=True)),
133
+ ] + list(
134
+ BuiltinFunction('abs', None, None, "/*abs_{0}*/".format(t.specialization_name()),
135
+ func_type = PyrexTypes.CFuncType(
136
+ t,
137
+ [PyrexTypes.CFuncTypeArg("arg", t, None)],
138
+ is_strict_signature = True, nogil=True))
139
+ for t in (PyrexTypes.c_uint_type, PyrexTypes.c_ulong_type, PyrexTypes.c_ulonglong_type)
140
+ ) + list(
141
+ BuiltinFunction('abs', None, None, "__Pyx_c_abs{0}".format(t.funcsuffix),
142
+ func_type = PyrexTypes.CFuncType(
143
+ t.real_type, [
144
+ PyrexTypes.CFuncTypeArg("arg", t, None)
145
+ ],
146
+ is_strict_signature = True, nogil=True))
147
+ for t in (PyrexTypes.c_float_complex_type,
148
+ PyrexTypes.c_double_complex_type,
149
+ PyrexTypes.c_longdouble_complex_type)
150
+ ) + [
151
+ BuiltinFunction('abs', "O", "O", "__Pyx_PyNumber_Absolute",
152
+ utility_code=UtilityCode.load("py_abs", "Builtins.c")),
153
+ #('all', "", "", ""),
154
+ #('any', "", "", ""),
155
+ #('ascii', "", "", ""),
156
+ #('bin', "", "", ""),
157
+ BuiltinFunction('callable', "O", "b", "__Pyx_PyCallable_Check",
158
+ utility_code = UtilityCode.load("CallableCheck", "ObjectHandling.c")),
159
+ #('chr', "", "", ""),
160
+ #('cmp', "", "", "", ""), # int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
161
+ #('compile', "", "", ""), # PyObject* Py_CompileString( char *str, char *filename, int start)
162
+ BuiltinFunction('delattr', "OO", "r", "PyObject_DelAttr"),
163
+ BuiltinFunction('dir', "O", "O", "PyObject_Dir"),
164
+ BuiltinFunction('divmod', "OO", "O", "PyNumber_Divmod"),
165
+ BuiltinFunction('exec', "O", "O", "__Pyx_PyExecGlobals",
166
+ utility_code = pyexec_globals_utility_code),
167
+ BuiltinFunction('exec', "OO", "O", "__Pyx_PyExec2",
168
+ utility_code = pyexec_utility_code),
169
+ BuiltinFunction('exec', "OOO", "O", "__Pyx_PyExec3",
170
+ utility_code = pyexec_utility_code),
171
+ #('eval', "", "", ""),
172
+ #('execfile', "", "", ""),
173
+ #('filter', "", "", ""),
174
+ BuiltinFunction('getattr3', "OOO", "O", "__Pyx_GetAttr3", "getattr",
175
+ utility_code=getattr3_utility_code), # Pyrex legacy
176
+ BuiltinFunction('getattr', "OOO", "O", "__Pyx_GetAttr3",
177
+ utility_code=getattr3_utility_code),
178
+ BuiltinFunction('getattr', "OO", "O", "__Pyx_GetAttr",
179
+ utility_code=getattr_utility_code),
180
+ BuiltinFunction('hasattr', "OO", "b", "__Pyx_HasAttr",
181
+ utility_code = UtilityCode.load("HasAttr", "Builtins.c")),
182
+ BuiltinFunction('hash', "O", "h", "PyObject_Hash"),
183
+ #('hex', "", "", ""),
184
+ #('id', "", "", ""),
185
+ #('input', "", "", ""),
186
+ BuiltinFunction('intern', "O", "O", "__Pyx_Intern",
187
+ utility_code = UtilityCode.load("Intern", "Builtins.c")),
188
+ BuiltinFunction('isinstance', "OO", "b", "PyObject_IsInstance"),
189
+ BuiltinFunction('issubclass', "OO", "b", "PyObject_IsSubclass"),
190
+ BuiltinFunction('iter', "OO", "O", "PyCallIter_New"),
191
+ BuiltinFunction('iter', "O", "O", "PyObject_GetIter"),
192
+ BuiltinFunction('len', "O", "z", "PyObject_Length"),
193
+ BuiltinFunction('locals', "", "O", "__pyx_locals"),
194
+ #('map', "", "", ""),
195
+ #('max', "", "", ""),
196
+ #('min', "", "", ""),
197
+ BuiltinFunction('next', "O", "O", "__Pyx_PyIter_Next",
198
+ utility_code = iter_next_utility_code), # not available in Py2 => implemented here
199
+ BuiltinFunction('next', "OO", "O", "__Pyx_PyIter_Next2",
200
+ utility_code = iter_next_utility_code), # not available in Py2 => implemented here
201
+ #('oct', "", "", ""),
202
+ #('open', "ss", "O", "PyFile_FromString"), # not in Py3
203
+ ] + [
204
+ BuiltinFunction('ord', None, None, "__Pyx_long_cast",
205
+ func_type=PyrexTypes.CFuncType(
206
+ PyrexTypes.c_long_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
207
+ is_strict_signature=True))
208
+ for c_type in [PyrexTypes.c_py_ucs4_type, PyrexTypes.c_py_unicode_type]
209
+ ] + [
210
+ BuiltinFunction('ord', None, None, "__Pyx_uchar_cast",
211
+ func_type=PyrexTypes.CFuncType(
212
+ PyrexTypes.c_uchar_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
213
+ is_strict_signature=True))
214
+ for c_type in [PyrexTypes.c_char_type, PyrexTypes.c_schar_type, PyrexTypes.c_uchar_type]
215
+ ] + [
216
+ BuiltinFunction('ord', None, None, "__Pyx_PyObject_Ord",
217
+ utility_code=UtilityCode.load_cached("object_ord", "Builtins.c"),
218
+ func_type=PyrexTypes.CFuncType(
219
+ PyrexTypes.c_long_type, [
220
+ PyrexTypes.CFuncTypeArg("c", PyrexTypes.py_object_type, None)
221
+ ],
222
+ exception_value="(long)(Py_UCS4)-1")),
223
+ BuiltinFunction('pow', "OOO", "O", "PyNumber_Power"),
224
+ BuiltinFunction('pow', "OO", "O", "__Pyx_PyNumber_Power2",
225
+ utility_code = UtilityCode.load("pow2", "Builtins.c")),
226
+ #('range', "", "", ""),
227
+ #('raw_input', "", "", ""),
228
+ #('reduce', "", "", ""),
229
+ BuiltinFunction('reload', "O", "O", "PyImport_ReloadModule"),
230
+ BuiltinFunction('repr', "O", "O", "PyObject_Repr"), # , builtin_return_type='str'), # add in Cython 3.1
231
+ #('round', "", "", ""),
232
+ BuiltinFunction('setattr', "OOO", "r", "PyObject_SetAttr"),
233
+ #('sum', "", "", ""),
234
+ #('sorted', "", "", ""),
235
+ #('type', "O", "O", "PyObject_Type"),
236
+ BuiltinFunction('unichr', "i", "O", "PyUnicode_FromOrdinal", builtin_return_type='unicode'),
237
+ #('unicode', "", "", ""),
238
+ #('vars', "", "", ""),
239
+ #('zip', "", "", ""),
240
+ # Can't do these easily until we have builtin type entries.
241
+ #('typecheck', "OO", "i", "PyObject_TypeCheck", False),
242
+ #('issubtype', "OO", "i", "PyType_IsSubtype", False),
243
+
244
+ # Put in namespace append optimization.
245
+ BuiltinFunction('__Pyx_PyObject_Append', "OO", "O", "__Pyx_PyObject_Append"),
246
+
247
+ # This is conditionally looked up based on a compiler directive.
248
+ BuiltinFunction('__Pyx_Globals', "", "O", "__Pyx_Globals",
249
+ utility_code=globals_utility_code),
250
+ ]
251
+
252
+
253
+ # Builtin types
254
+ # bool
255
+ # buffer
256
+ # classmethod
257
+ # dict
258
+ # enumerate
259
+ # file
260
+ # float
261
+ # int
262
+ # list
263
+ # long
264
+ # object
265
+ # property
266
+ # slice
267
+ # staticmethod
268
+ # super
269
+ # str
270
+ # tuple
271
+ # type
272
+ # xrange
273
+
274
+ builtin_types_table = [
275
+
276
+ ("type", "PyType_Type", []),
277
+
278
+ # This conflicts with the C++ bool type, and unfortunately
279
+ # C++ is too liberal about PyObject* <-> bool conversions,
280
+ # resulting in unintuitive runtime behavior and segfaults.
281
+ # ("bool", "PyBool_Type", []),
282
+
283
+ ("int", "PyInt_Type", []),
284
+ ("long", "PyLong_Type", []),
285
+ ("float", "PyFloat_Type", []),
286
+
287
+ ("complex", "PyComplex_Type", [BuiltinAttribute('cval', field_type_name = 'Py_complex'),
288
+ BuiltinAttribute('real', 'cval.real', field_type = PyrexTypes.c_double_type),
289
+ BuiltinAttribute('imag', 'cval.imag', field_type = PyrexTypes.c_double_type),
290
+ ]),
291
+
292
+ ("basestring", "PyBaseString_Type", [
293
+ BuiltinMethod("join", "TO", "T", "__Pyx_PyBaseString_Join",
294
+ utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
295
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
296
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
297
+ ]),
298
+ ("bytearray", "PyByteArray_Type", [
299
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
300
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
301
+ ]),
302
+ ("bytes", "PyBytes_Type", [BuiltinMethod("join", "TO", "O", "__Pyx_PyBytes_Join",
303
+ utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
304
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
305
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
306
+ ]),
307
+ ("str", "PyString_Type", [BuiltinMethod("join", "TO", "O", "__Pyx_PyString_Join",
308
+ builtin_return_type='basestring',
309
+ utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
310
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
311
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
312
+ ]),
313
+ ("unicode", "PyUnicode_Type", [BuiltinMethod("__contains__", "TO", "b", "PyUnicode_Contains"),
314
+ BuiltinMethod("join", "TO", "T", "PyUnicode_Join"),
315
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
316
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
317
+ ]),
318
+
319
+ ("tuple", "PyTuple_Type", [BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
320
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
321
+ ]),
322
+
323
+ ("list", "PyList_Type", [BuiltinMethod("insert", "TzO", "r", "PyList_Insert"),
324
+ BuiltinMethod("reverse", "T", "r", "PyList_Reverse"),
325
+ BuiltinMethod("append", "TO", "r", "__Pyx_PyList_Append",
326
+ utility_code=UtilityCode.load("ListAppend", "Optimize.c")),
327
+ BuiltinMethod("extend", "TO", "r", "__Pyx_PyList_Extend",
328
+ utility_code=UtilityCode.load("ListExtend", "Optimize.c")),
329
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
330
+ utility_code=UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")),
331
+ ]),
332
+
333
+ ("dict", "PyDict_Type", [BuiltinMethod("__contains__", "TO", "b", "PyDict_Contains"),
334
+ BuiltinMethod("has_key", "TO", "b", "PyDict_Contains"),
335
+ BuiltinMethod("items", "T", "O", "__Pyx_PyDict_Items",
336
+ utility_code=UtilityCode.load("py_dict_items", "Builtins.c")),
337
+ BuiltinMethod("keys", "T", "O", "__Pyx_PyDict_Keys",
338
+ utility_code=UtilityCode.load("py_dict_keys", "Builtins.c")),
339
+ BuiltinMethod("values", "T", "O", "__Pyx_PyDict_Values",
340
+ utility_code=UtilityCode.load("py_dict_values", "Builtins.c")),
341
+ BuiltinMethod("iteritems", "T", "O", "__Pyx_PyDict_IterItems",
342
+ utility_code=UtilityCode.load("py_dict_iteritems", "Builtins.c")),
343
+ BuiltinMethod("iterkeys", "T", "O", "__Pyx_PyDict_IterKeys",
344
+ utility_code=UtilityCode.load("py_dict_iterkeys", "Builtins.c")),
345
+ BuiltinMethod("itervalues", "T", "O", "__Pyx_PyDict_IterValues",
346
+ utility_code=UtilityCode.load("py_dict_itervalues", "Builtins.c")),
347
+ BuiltinMethod("viewitems", "T", "O", "__Pyx_PyDict_ViewItems",
348
+ utility_code=UtilityCode.load("py_dict_viewitems", "Builtins.c")),
349
+ BuiltinMethod("viewkeys", "T", "O", "__Pyx_PyDict_ViewKeys",
350
+ utility_code=UtilityCode.load("py_dict_viewkeys", "Builtins.c")),
351
+ BuiltinMethod("viewvalues", "T", "O", "__Pyx_PyDict_ViewValues",
352
+ utility_code=UtilityCode.load("py_dict_viewvalues", "Builtins.c")),
353
+ BuiltinMethod("clear", "T", "r", "__Pyx_PyDict_Clear",
354
+ utility_code=UtilityCode.load("py_dict_clear", "Optimize.c")),
355
+ BuiltinMethod("copy", "T", "T", "PyDict_Copy")]),
356
+
357
+ ("slice", "PySlice_Type", [BuiltinAttribute('start'),
358
+ BuiltinAttribute('stop'),
359
+ BuiltinAttribute('step'),
360
+ ]),
361
+ # ("file", "PyFile_Type", []), # not in Py3
362
+
363
+ ("set", "PySet_Type", [BuiltinMethod("clear", "T", "r", "PySet_Clear"),
364
+ # discard() and remove() have a special treatment for unhashable values
365
+ BuiltinMethod("discard", "TO", "r", "__Pyx_PySet_Discard",
366
+ utility_code=UtilityCode.load("py_set_discard", "Optimize.c")),
367
+ BuiltinMethod("remove", "TO", "r", "__Pyx_PySet_Remove",
368
+ utility_code=UtilityCode.load("py_set_remove", "Optimize.c")),
369
+ # update is actually variadic (see Github issue #1645)
370
+ # BuiltinMethod("update", "TO", "r", "__Pyx_PySet_Update",
371
+ # utility_code=UtilityCode.load_cached("PySet_Update", "Builtins.c")),
372
+ BuiltinMethod("add", "TO", "r", "PySet_Add"),
373
+ BuiltinMethod("pop", "T", "O", "PySet_Pop")]),
374
+ ("frozenset", "PyFrozenSet_Type", []),
375
+ ("Exception", "((PyTypeObject*)PyExc_Exception)[0]", []),
376
+ ("StopAsyncIteration", "((PyTypeObject*)__Pyx_PyExc_StopAsyncIteration)[0]", []),
377
+ ("memoryview", "PyMemoryView_Type", [
378
+ # TODO - format would be nice, but hard to get
379
+ # __len__ can be accessed through a direct lookup of the buffer (but probably in Optimize.c)
380
+ # error checking would ideally be limited api only
381
+ BuiltinProperty("ndim", PyrexTypes.c_int_type, '__Pyx_PyMemoryView_Get_ndim',
382
+ exception_value="-1", exception_check=True,
383
+ utility_code=TempitaUtilityCode.load_cached(
384
+ "memoryview_get_from_buffer", "Builtins.c",
385
+ context=dict(name="ndim")
386
+ )
387
+ ),
388
+ BuiltinProperty("readonly", PyrexTypes.c_bint_type, '__Pyx_PyMemoryView_Get_readonly',
389
+ exception_value="-1", exception_check=True,
390
+ utility_code=TempitaUtilityCode.load_cached(
391
+ "memoryview_get_from_buffer", "Builtins.c",
392
+ context=dict(name="readonly")
393
+ )
394
+ ),
395
+ BuiltinProperty("itemsize", PyrexTypes.c_py_ssize_t_type, '__Pyx_PyMemoryView_Get_itemsize',
396
+ exception_value="-1", exception_check=True,
397
+ utility_code=TempitaUtilityCode.load_cached(
398
+ "memoryview_get_from_buffer", "Builtins.c",
399
+ context=dict(name="itemsize")
400
+ )
401
+ )]
402
+ )
403
+ ]
404
+
405
+
406
+ types_that_construct_their_instance = frozenset({
407
+ # some builtin types do not always return an instance of
408
+ # themselves - these do:
409
+ 'type', 'bool', 'long', 'float', 'complex',
410
+ 'bytes', 'unicode', 'bytearray',
411
+ 'tuple', 'list', 'dict', 'set', 'frozenset',
412
+ # 'str', # only in Py3.x
413
+ # 'file', # only in Py2.x
414
+ 'memoryview'
415
+ })
416
+
417
+
418
+ builtin_structs_table = [
419
+ ('Py_buffer', 'Py_buffer',
420
+ [("buf", PyrexTypes.c_void_ptr_type),
421
+ ("obj", PyrexTypes.py_object_type),
422
+ ("len", PyrexTypes.c_py_ssize_t_type),
423
+ ("itemsize", PyrexTypes.c_py_ssize_t_type),
424
+ ("readonly", PyrexTypes.c_bint_type),
425
+ ("ndim", PyrexTypes.c_int_type),
426
+ ("format", PyrexTypes.c_char_ptr_type),
427
+ ("shape", PyrexTypes.c_py_ssize_t_ptr_type),
428
+ ("strides", PyrexTypes.c_py_ssize_t_ptr_type),
429
+ ("suboffsets", PyrexTypes.c_py_ssize_t_ptr_type),
430
+ ("smalltable", PyrexTypes.CArrayType(PyrexTypes.c_py_ssize_t_type, 2)),
431
+ ("internal", PyrexTypes.c_void_ptr_type),
432
+ ]),
433
+ ('Py_complex', 'Py_complex',
434
+ [('real', PyrexTypes.c_double_type),
435
+ ('imag', PyrexTypes.c_double_type),
436
+ ])
437
+ ]
438
+
439
+ # set up builtin scope
440
+
441
+ builtin_scope = BuiltinScope()
442
+
443
+ def init_builtin_funcs():
444
+ for bf in builtin_function_table:
445
+ bf.declare_in_scope(builtin_scope)
446
+
447
+ builtin_types = {}
448
+
449
+ def init_builtin_types():
450
+ global builtin_types
451
+ for name, cname, methods in builtin_types_table:
452
+ utility = builtin_utility_code.get(name)
453
+ if name == 'frozenset':
454
+ objstruct_cname = 'PySetObject'
455
+ elif name == 'bytearray':
456
+ objstruct_cname = 'PyByteArrayObject'
457
+ elif name == 'bool':
458
+ objstruct_cname = None
459
+ elif name == 'Exception':
460
+ objstruct_cname = "PyBaseExceptionObject"
461
+ elif name == 'StopAsyncIteration':
462
+ objstruct_cname = "PyBaseExceptionObject"
463
+ else:
464
+ objstruct_cname = 'Py%sObject' % name.capitalize()
465
+ type_class = PyrexTypes.BuiltinObjectType
466
+ if name in ['dict', 'list', 'set', 'frozenset']:
467
+ type_class = PyrexTypes.BuiltinTypeConstructorObjectType
468
+ elif name == 'tuple':
469
+ type_class = PyrexTypes.PythonTupleTypeConstructor
470
+ the_type = builtin_scope.declare_builtin_type(name, cname, utility, objstruct_cname,
471
+ type_class=type_class)
472
+ builtin_types[name] = the_type
473
+ for method in methods:
474
+ method.declare_in_type(the_type)
475
+
476
+ def init_builtin_structs():
477
+ for name, cname, attribute_types in builtin_structs_table:
478
+ scope = StructOrUnionScope(name)
479
+ for attribute_name, attribute_type in attribute_types:
480
+ scope.declare_var(attribute_name, attribute_type, None,
481
+ attribute_name, allow_pyobject=True)
482
+ builtin_scope.declare_struct_or_union(
483
+ name, "struct", scope, 1, None, cname = cname)
484
+
485
+
486
+ def init_builtins():
487
+ #Errors.init_thread() # hopefully not needed - we should not emit warnings ourselves
488
+ init_builtin_structs()
489
+ init_builtin_types()
490
+ init_builtin_funcs()
491
+
492
+ entry = builtin_scope.declare_var(
493
+ '__debug__', PyrexTypes.c_const_type(PyrexTypes.c_bint_type),
494
+ pos=None, cname='__pyx_assertions_enabled()', is_cdef=True)
495
+ entry.utility_code = UtilityCode.load_cached("AssertionsEnabled", "Exceptions.c")
496
+
497
+ global type_type, list_type, tuple_type, dict_type, set_type, frozenset_type, slice_type
498
+ global bytes_type, str_type, unicode_type, basestring_type, bytearray_type
499
+ global float_type, int_type, long_type, bool_type, complex_type
500
+ global memoryview_type, py_buffer_type
501
+ global sequence_types
502
+ type_type = builtin_scope.lookup('type').type
503
+ list_type = builtin_scope.lookup('list').type
504
+ tuple_type = builtin_scope.lookup('tuple').type
505
+ dict_type = builtin_scope.lookup('dict').type
506
+ set_type = builtin_scope.lookup('set').type
507
+ frozenset_type = builtin_scope.lookup('frozenset').type
508
+ slice_type = builtin_scope.lookup('slice').type
509
+
510
+ bytes_type = builtin_scope.lookup('bytes').type
511
+ str_type = builtin_scope.lookup('str').type
512
+ unicode_type = builtin_scope.lookup('unicode').type
513
+ basestring_type = builtin_scope.lookup('basestring').type
514
+ bytearray_type = builtin_scope.lookup('bytearray').type
515
+ memoryview_type = builtin_scope.lookup('memoryview').type
516
+
517
+ float_type = builtin_scope.lookup('float').type
518
+ int_type = builtin_scope.lookup('int').type
519
+ long_type = builtin_scope.lookup('long').type
520
+ bool_type = builtin_scope.lookup('bool').type
521
+ complex_type = builtin_scope.lookup('complex').type
522
+
523
+ sequence_types = (
524
+ list_type,
525
+ tuple_type,
526
+ bytes_type,
527
+ str_type,
528
+ unicode_type,
529
+ basestring_type,
530
+ bytearray_type,
531
+ memoryview_type,
532
+ )
533
+
534
+ # Set up type inference links between equivalent Python/C types
535
+ bool_type.equivalent_type = PyrexTypes.c_bint_type
536
+ PyrexTypes.c_bint_type.equivalent_type = bool_type
537
+
538
+ float_type.equivalent_type = PyrexTypes.c_double_type
539
+ PyrexTypes.c_double_type.equivalent_type = float_type
540
+
541
+ complex_type.equivalent_type = PyrexTypes.c_double_complex_type
542
+ PyrexTypes.c_double_complex_type.equivalent_type = complex_type
543
+
544
+ py_buffer_type = builtin_scope.lookup('Py_buffer').type
545
+
546
+
547
+ init_builtins()
548
+
549
+ ##############################
550
+ # Support for a few standard library modules that Cython understands (currently typing and dataclasses)
551
+ ##############################
552
+ _known_module_scopes = {}
553
+
554
+ def get_known_standard_library_module_scope(module_name):
555
+ mod = _known_module_scopes.get(module_name)
556
+ if mod:
557
+ return mod
558
+
559
+ if module_name == "typing":
560
+ mod = ModuleScope(module_name, None, None)
561
+ for name, tp in [
562
+ ('Dict', dict_type),
563
+ ('List', list_type),
564
+ ('Tuple', tuple_type),
565
+ ('Set', set_type),
566
+ ('FrozenSet', frozenset_type),
567
+ ]:
568
+ name = EncodedString(name)
569
+ entry = mod.declare_type(name, tp, pos = None)
570
+ var_entry = Entry(name, None, PyrexTypes.py_object_type)
571
+ var_entry.is_pyglobal = True
572
+ var_entry.is_variable = True
573
+ var_entry.scope = mod
574
+ entry.as_variable = var_entry
575
+ entry.known_standard_library_import = "%s.%s" % (module_name, name)
576
+
577
+ for name in ['ClassVar', 'Optional']:
578
+ name = EncodedString(name)
579
+ indexed_type = PyrexTypes.SpecialPythonTypeConstructor(EncodedString("typing."+name))
580
+ entry = mod.declare_type(name, indexed_type, pos = None)
581
+ var_entry = Entry(name, None, PyrexTypes.py_object_type)
582
+ var_entry.is_pyglobal = True
583
+ var_entry.is_variable = True
584
+ var_entry.scope = mod
585
+ entry.as_variable = var_entry
586
+ entry.known_standard_library_import = "%s.%s" % (module_name, name)
587
+ _known_module_scopes[module_name] = mod
588
+ elif module_name == "dataclasses":
589
+ mod = ModuleScope(module_name, None, None)
590
+ indexed_type = PyrexTypes.SpecialPythonTypeConstructor(EncodedString("dataclasses.InitVar"))
591
+ initvar_string = EncodedString("InitVar")
592
+ entry = mod.declare_type(initvar_string, indexed_type, pos = None)
593
+ var_entry = Entry(initvar_string, None, PyrexTypes.py_object_type)
594
+ var_entry.is_pyglobal = True
595
+ var_entry.scope = mod
596
+ entry.as_variable = var_entry
597
+ entry.known_standard_library_import = "%s.InitVar" % module_name
598
+ for name in ["dataclass", "field"]:
599
+ mod.declare_var(EncodedString(name), PyrexTypes.py_object_type, pos=None)
600
+ _known_module_scopes[module_name] = mod
601
+ elif module_name == "functools":
602
+ mod = ModuleScope(module_name, None, None)
603
+ for name in ["total_ordering"]:
604
+ mod.declare_var(EncodedString(name), PyrexTypes.py_object_type, pos=None)
605
+ _known_module_scopes[module_name] = mod
606
+
607
+ return mod
608
+
609
+
610
+ def get_known_standard_library_entry(qualified_name):
611
+ name_parts = qualified_name.split(".")
612
+ module_name = EncodedString(name_parts[0])
613
+ rest = name_parts[1:]
614
+
615
+ if len(rest) > 1: # for now, we don't know how to deal with any nested modules
616
+ return None
617
+
618
+ mod = get_known_standard_library_module_scope(module_name)
619
+
620
+ # eventually handle more sophisticated multiple lookups if needed
621
+ if mod and rest:
622
+ return mod.lookup_here(rest[0])
623
+ return None
624
+
625
+
626
+ def exprnode_to_known_standard_library_name(node, env):
627
+ qualified_name_parts = []
628
+ known_name = None
629
+ while node.is_attribute:
630
+ qualified_name_parts.append(node.attribute)
631
+ node = node.obj
632
+ if node.is_name:
633
+ entry = env.lookup(node.name)
634
+ if entry and entry.known_standard_library_import:
635
+ if get_known_standard_library_entry(
636
+ entry.known_standard_library_import):
637
+ known_name = entry.known_standard_library_import
638
+ else:
639
+ standard_env = get_known_standard_library_module_scope(
640
+ entry.known_standard_library_import)
641
+ if standard_env:
642
+ qualified_name_parts.append(standard_env.name)
643
+ known_name = ".".join(reversed(qualified_name_parts))
644
+ return known_name
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Code.pxd ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ cimport cython
4
+ from ..StringIOTree cimport StringIOTree
5
+
6
+
7
+ cdef class UtilityCodeBase(object):
8
+ cpdef format_code(self, code_string, replace_empty_lines=*)
9
+
10
+
11
+ cdef class UtilityCode(UtilityCodeBase):
12
+ cdef public object name
13
+ cdef public object proto
14
+ cdef public object impl
15
+ cdef public object init
16
+ cdef public object cleanup
17
+ cdef public object proto_block
18
+ cdef public object requires
19
+ cdef public dict _cache
20
+ cdef public list specialize_list
21
+ cdef public object file
22
+
23
+ cpdef none_or_sub(self, s, context)
24
+
25
+
26
+ cdef class FunctionState:
27
+ cdef public set names_taken
28
+ cdef public object owner
29
+ cdef public object scope
30
+
31
+ cdef public object error_label
32
+ cdef public size_t label_counter
33
+ cdef public set labels_used
34
+ cdef public object return_label
35
+ cdef public object continue_label
36
+ cdef public object break_label
37
+ cdef public list yield_labels
38
+
39
+ cdef public object return_from_error_cleanup_label # not used in __init__ ?
40
+
41
+ cdef public object exc_vars
42
+ cdef public object current_except
43
+ cdef public bint in_try_finally
44
+ cdef public bint can_trace
45
+ cdef public bint gil_owned
46
+
47
+ cdef public list temps_allocated
48
+ cdef public dict temps_free
49
+ cdef public dict temps_used_type
50
+ cdef public set zombie_temps
51
+ cdef public size_t temp_counter
52
+ cdef public list collect_temps_stack
53
+
54
+ cdef public object closure_temps
55
+ cdef public bint should_declare_error_indicator
56
+ cdef public bint uses_error_indicator
57
+ cdef public bint error_without_exception
58
+
59
+ cdef public bint needs_refnanny
60
+
61
+ @cython.locals(n=size_t)
62
+ cpdef new_label(self, name=*)
63
+ cpdef tuple get_loop_labels(self)
64
+ cpdef set_loop_labels(self, labels)
65
+ cpdef tuple get_all_labels(self)
66
+ cpdef set_all_labels(self, labels)
67
+ cpdef start_collecting_temps(self)
68
+ cpdef stop_collecting_temps(self)
69
+
70
+ cpdef list temps_in_use(self)
71
+
72
+ cdef class IntConst:
73
+ cdef public object cname
74
+ cdef public object value
75
+ cdef public bint is_long
76
+
77
+ cdef class PyObjectConst:
78
+ cdef public object cname
79
+ cdef public object type
80
+
81
+ cdef class StringConst:
82
+ cdef public object cname
83
+ cdef public object text
84
+ cdef public object escaped_value
85
+ cdef public dict py_strings
86
+ cdef public list py_versions
87
+
88
+ @cython.locals(intern=bint, is_str=bint, is_unicode=bint)
89
+ cpdef get_py_string_const(self, encoding, identifier=*, is_str=*, py3str_cstring=*)
90
+
91
+ ## cdef class PyStringConst:
92
+ ## cdef public object cname
93
+ ## cdef public object encoding
94
+ ## cdef public bint is_str
95
+ ## cdef public bint is_unicode
96
+ ## cdef public bint intern
97
+
98
+ #class GlobalState(object):
99
+
100
+ #def funccontext_property(name):
101
+
102
+ cdef class CCodeWriter(object):
103
+ cdef readonly StringIOTree buffer
104
+ cdef readonly list pyclass_stack
105
+ cdef readonly object globalstate
106
+ cdef readonly object funcstate
107
+ cdef object code_config
108
+ cdef object last_pos
109
+ cdef object last_marked_pos
110
+ cdef Py_ssize_t level
111
+ cdef public Py_ssize_t call_level # debug-only, see Nodes.py
112
+ cdef bint bol
113
+
114
+ cpdef write(self, s)
115
+ @cython.final
116
+ cdef _write_lines(self, s)
117
+ cpdef _write_to_buffer(self, s)
118
+ cpdef put(self, code)
119
+ cpdef put_safe(self, code)
120
+ cpdef putln(self, code=*, bint safe=*)
121
+ @cython.final
122
+ cdef increase_indent(self)
123
+ @cython.final
124
+ cdef decrease_indent(self)
125
+ @cython.final
126
+ cdef indent(self)
127
+
128
+
129
+ cdef class PyrexCodeWriter:
130
+ cdef public object f
131
+ cdef public Py_ssize_t level
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/CodeGeneration.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from .Visitor import VisitorTransform
4
+ from .Nodes import StatListNode
5
+
6
+
7
+ class ExtractPxdCode(VisitorTransform):
8
+ """
9
+ Finds nodes in a pxd file that should generate code, and
10
+ returns them in a StatListNode.
11
+
12
+ The result is a tuple (StatListNode, ModuleScope), i.e.
13
+ everything that is needed from the pxd after it is processed.
14
+
15
+ A purer approach would be to separately compile the pxd code,
16
+ but the result would have to be slightly more sophisticated
17
+ than pure strings (functions + wanted interned strings +
18
+ wanted utility code + wanted cached objects) so for now this
19
+ approach is taken.
20
+ """
21
+
22
+ def __call__(self, root):
23
+ self.funcs = []
24
+ self.visitchildren(root)
25
+ return (StatListNode(root.pos, stats=self.funcs), root.scope)
26
+
27
+ def visit_FuncDefNode(self, node):
28
+ self.funcs.append(node)
29
+ # Do not visit children, nested funcdefnodes will
30
+ # also be moved by this action...
31
+ return node
32
+
33
+ def visit_Node(self, node):
34
+ self.visitchildren(node)
35
+ return node
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Future.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def _get_feature(name):
2
+ import __future__
3
+ # fall back to a unique fake object for earlier Python versions or Python 3
4
+ return getattr(__future__, name, object())
5
+
6
+ unicode_literals = _get_feature("unicode_literals")
7
+ with_statement = _get_feature("with_statement") # dummy
8
+ division = _get_feature("division")
9
+ print_function = _get_feature("print_function")
10
+ absolute_import = _get_feature("absolute_import")
11
+ nested_scopes = _get_feature("nested_scopes") # dummy
12
+ generators = _get_feature("generators") # dummy
13
+ generator_stop = _get_feature("generator_stop")
14
+ annotations = _get_feature("annotations")
15
+
16
+ del _get_feature
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Interpreter.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module deals with interpreting the parse tree as Python
3
+ would have done, in the compiler.
4
+
5
+ For now this only covers parse tree to value conversion of
6
+ compile-time values.
7
+ """
8
+
9
+ from __future__ import absolute_import
10
+
11
+ from .Nodes import *
12
+ from .ExprNodes import *
13
+ from .Errors import CompileError
14
+
15
+
16
+ class EmptyScope(object):
17
+ def lookup(self, name):
18
+ return None
19
+
20
+ empty_scope = EmptyScope()
21
+
22
+ def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()):
23
+ """
24
+ Tries to interpret a list of compile time option nodes.
25
+ The result will be a tuple (optlist, optdict) but where
26
+ all expression nodes have been interpreted. The result is
27
+ in the form of tuples (value, pos).
28
+
29
+ optlist is a list of nodes, while optdict is a DictNode (the
30
+ result optdict is a dict)
31
+
32
+ If type_env is set, all type nodes will be analysed and the resulting
33
+ type set. Otherwise only interpretateable ExprNodes
34
+ are allowed, other nodes raises errors.
35
+
36
+ A CompileError will be raised if there are problems.
37
+ """
38
+
39
+ def interpret(node, ix):
40
+ if ix in type_args:
41
+ if type_env:
42
+ type = node.analyse_as_type(type_env)
43
+ if not type:
44
+ raise CompileError(node.pos, "Invalid type.")
45
+ return (type, node.pos)
46
+ else:
47
+ raise CompileError(node.pos, "Type not allowed here.")
48
+ else:
49
+ if (sys.version_info[0] >=3 and
50
+ isinstance(node, StringNode) and
51
+ node.unicode_value is not None):
52
+ return (node.unicode_value, node.pos)
53
+ return (node.compile_time_value(empty_scope), node.pos)
54
+
55
+ if optlist:
56
+ optlist = [interpret(x, ix) for ix, x in enumerate(optlist)]
57
+ if optdict:
58
+ assert isinstance(optdict, DictNode)
59
+ new_optdict = {}
60
+ for item in optdict.key_value_pairs:
61
+ new_key, dummy = interpret(item.key, None)
62
+ new_optdict[new_key] = interpret(item.value, item.key.value)
63
+ optdict = new_optdict
64
+ return (optlist, new_optdict)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Lexicon.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # cython: language_level=3, py2_import=True
3
+ #
4
+ # Cython Scanner - Lexical Definitions
5
+ #
6
+
7
+ from __future__ import absolute_import, unicode_literals
8
+
9
+ raw_prefixes = "rR"
10
+ bytes_prefixes = "bB"
11
+ string_prefixes = "fFuU" + bytes_prefixes
12
+ char_prefixes = "cC"
13
+ any_string_prefix = raw_prefixes + string_prefixes + char_prefixes
14
+ IDENT = 'IDENT'
15
+
16
+
17
+ def make_lexicon():
18
+ from ..Plex import \
19
+ Str, Any, AnyBut, AnyChar, Rep, Rep1, Opt, Bol, Eol, Eof, \
20
+ TEXT, IGNORE, Method, State, Lexicon, Range
21
+
22
+ nonzero_digit = Any("123456789")
23
+ digit = Any("0123456789")
24
+ bindigit = Any("01")
25
+ octdigit = Any("01234567")
26
+ hexdigit = Any("0123456789ABCDEFabcdef")
27
+ indentation = Bol + Rep(Any(" \t"))
28
+
29
+ # The list of valid unicode identifier characters are pretty slow to generate at runtime,
30
+ # and require Python3, so are just included directly here
31
+ # (via the generated code block at the bottom of the file)
32
+ unicode_start_character = (Any(unicode_start_ch_any) | Range(unicode_start_ch_range))
33
+ unicode_continuation_character = (
34
+ unicode_start_character |
35
+ Any(unicode_continuation_ch_any) | Range(unicode_continuation_ch_range))
36
+
37
+ def underscore_digits(d):
38
+ return Rep1(d) + Rep(Str("_") + Rep1(d))
39
+
40
+ def prefixed_digits(prefix, digits):
41
+ return prefix + Opt(Str("_")) + underscore_digits(digits)
42
+
43
+ decimal = underscore_digits(digit)
44
+ dot = Str(".")
45
+ exponent = Any("Ee") + Opt(Any("+-")) + decimal
46
+ decimal_fract = (decimal + dot + Opt(decimal)) | (dot + decimal)
47
+
48
+ #name = letter + Rep(letter | digit)
49
+ name = unicode_start_character + Rep(unicode_continuation_character)
50
+ intconst = (prefixed_digits(nonzero_digit, digit) | # decimal literals with underscores must not start with '0'
51
+ (Str("0") + (prefixed_digits(Any("Xx"), hexdigit) |
52
+ prefixed_digits(Any("Oo"), octdigit) |
53
+ prefixed_digits(Any("Bb"), bindigit) )) |
54
+ underscore_digits(Str('0')) # 0_0_0_0... is allowed as a decimal literal
55
+ | Rep1(digit) # FIXME: remove these Py2 style decimal/octal literals (PY_VERSION_HEX < 3)
56
+ )
57
+ intsuffix = (Opt(Any("Uu")) + Opt(Any("Ll")) + Opt(Any("Ll"))) | (Opt(Any("Ll")) + Opt(Any("Ll")) + Opt(Any("Uu")))
58
+ intliteral = intconst + intsuffix
59
+ fltconst = (decimal_fract + Opt(exponent)) | (decimal + exponent)
60
+ imagconst = (intconst | fltconst) + Any("jJ")
61
+
62
+ # invalid combinations of prefixes are caught in p_string_literal
63
+ beginstring = Opt(Rep(Any(string_prefixes + raw_prefixes)) |
64
+ Any(char_prefixes)
65
+ ) + (Str("'") | Str('"') | Str("'''") | Str('"""'))
66
+ two_oct = octdigit + octdigit
67
+ three_oct = octdigit + octdigit + octdigit
68
+ two_hex = hexdigit + hexdigit
69
+ four_hex = two_hex + two_hex
70
+ escapeseq = Str("\\") + (two_oct | three_oct |
71
+ Str('N{') + Rep(AnyBut('}')) + Str('}') |
72
+ Str('u') + four_hex | Str('x') + two_hex |
73
+ Str('U') + four_hex + four_hex | AnyChar)
74
+
75
+ bra = Any("([{")
76
+ ket = Any(")]}")
77
+ ellipsis = Str("...")
78
+ punct = Any(":,;+-*/|&<>=.%`~^?!@")
79
+ diphthong = Str("==", "<>", "!=", "<=", ">=", "<<", ">>", "**", "//",
80
+ "+=", "-=", "*=", "/=", "%=", "|=", "^=", "&=",
81
+ "<<=", ">>=", "**=", "//=", "->", "@=", "&&", "||", ':=')
82
+ spaces = Rep1(Any(" \t\f"))
83
+ escaped_newline = Str("\\\n")
84
+ lineterm = Eol + Opt(Str("\n"))
85
+
86
+ comment = Str("#") + Rep(AnyBut("\n"))
87
+
88
+ return Lexicon([
89
+ (name, Method('normalize_ident')),
90
+ (intliteral, Method('strip_underscores', symbol='INT')),
91
+ (fltconst, Method('strip_underscores', symbol='FLOAT')),
92
+ (imagconst, Method('strip_underscores', symbol='IMAG')),
93
+ (ellipsis | punct | diphthong, TEXT),
94
+
95
+ (bra, Method('open_bracket_action')),
96
+ (ket, Method('close_bracket_action')),
97
+ (lineterm, Method('newline_action')),
98
+
99
+ (beginstring, Method('begin_string_action')),
100
+
101
+ (comment, IGNORE),
102
+ (spaces, IGNORE),
103
+ (escaped_newline, IGNORE),
104
+
105
+ State('INDENT', [
106
+ (comment + lineterm, Method('commentline')),
107
+ (Opt(spaces) + Opt(comment) + lineterm, IGNORE),
108
+ (indentation, Method('indentation_action')),
109
+ (Eof, Method('eof_action'))
110
+ ]),
111
+
112
+ State('SQ_STRING', [
113
+ (escapeseq, 'ESCAPE'),
114
+ (Rep1(AnyBut("'\"\n\\")), 'CHARS'),
115
+ (Str('"'), 'CHARS'),
116
+ (Str("\n"), Method('unclosed_string_action')),
117
+ (Str("'"), Method('end_string_action')),
118
+ (Eof, 'EOF')
119
+ ]),
120
+
121
+ State('DQ_STRING', [
122
+ (escapeseq, 'ESCAPE'),
123
+ (Rep1(AnyBut('"\n\\')), 'CHARS'),
124
+ (Str("'"), 'CHARS'),
125
+ (Str("\n"), Method('unclosed_string_action')),
126
+ (Str('"'), Method('end_string_action')),
127
+ (Eof, 'EOF')
128
+ ]),
129
+
130
+ State('TSQ_STRING', [
131
+ (escapeseq, 'ESCAPE'),
132
+ (Rep1(AnyBut("'\"\n\\")), 'CHARS'),
133
+ (Any("'\""), 'CHARS'),
134
+ (Str("\n"), 'NEWLINE'),
135
+ (Str("'''"), Method('end_string_action')),
136
+ (Eof, 'EOF')
137
+ ]),
138
+
139
+ State('TDQ_STRING', [
140
+ (escapeseq, 'ESCAPE'),
141
+ (Rep1(AnyBut('"\'\n\\')), 'CHARS'),
142
+ (Any("'\""), 'CHARS'),
143
+ (Str("\n"), 'NEWLINE'),
144
+ (Str('"""'), Method('end_string_action')),
145
+ (Eof, 'EOF')
146
+ ]),
147
+
148
+ (Eof, Method('eof_action'))
149
+ ],
150
+
151
+ # FIXME: Plex 1.9 needs different args here from Plex 1.1.4
152
+ #debug_flags = scanner_debug_flags,
153
+ #debug_file = scanner_dump_file
154
+ )
155
+
156
+
157
+ # BEGIN GENERATED CODE
158
+ # Generated with 'cython-generate-lexicon.py' from:
159
+ # cpython 3.12.0a7+ (heads/master:4cd1cc843a, Apr 11 2023, 10:32:26) [GCC 11.3.0]
160
+
161
+ unicode_start_ch_any = (
162
+ u"\u005f\u00aa\u00b5\u00ba\u02ec\u02ee\u037f\u0386\u038c\u0559\u06d5"
163
+ u"\u06ff\u0710\u07b1\u07fa\u081a\u0824\u0828\u093d\u0950\u09b2\u09bd"
164
+ u"\u09ce\u09fc\u0a5e\u0abd\u0ad0\u0af9\u0b3d\u0b71\u0b83\u0b9c\u0bd0"
165
+ u"\u0c3d\u0c5d\u0c80\u0cbd\u0d3d\u0d4e\u0dbd\u0e32\u0e84\u0ea5\u0eb2"
166
+ u"\u0ebd\u0ec6\u0f00\u103f\u1061\u108e\u10c7\u10cd\u1258\u12c0\u17d7"
167
+ u"\u17dc\u18aa\u1aa7\u1cfa\u1f59\u1f5b\u1f5d\u1fbe\u2071\u207f\u2102"
168
+ u"\u2107\u2115\u2124\u2126\u2128\u214e\u2d27\u2d2d\u2d6f\ua7d3\ua8fb"
169
+ u"\ua9cf\uaa7a\uaab1\uaac0\uaac2\ufb1d\ufb3e\ufe71\ufe73\ufe77\ufe79"
170
+ u"\ufe7b\ufe7d\U00010808\U0001083c\U00010a00\U00010f27\U00011075\U00011144\U00011147\U00011176\U000111da"
171
+ u"\U000111dc\U00011288\U0001133d\U00011350\U000114c7\U00011644\U000116b8\U00011909\U0001193f\U00011941\U000119e1"
172
+ u"\U000119e3\U00011a00\U00011a3a\U00011a50\U00011a9d\U00011c40\U00011d46\U00011d98\U00011f02\U00011fb0\U00016f50"
173
+ u"\U00016fe3\U0001b132\U0001b155\U0001d4a2\U0001d4bb\U0001d546\U0001e14e\U0001e94b\U0001ee24\U0001ee27\U0001ee39"
174
+ u"\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f"
175
+ u"\U0001ee64\U0001ee7e"
176
+ )
177
+ unicode_start_ch_range = (
178
+ u"\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6\u00f8\u02c1\u02c6"
179
+ u"\u02d1\u02e0\u02e4\u0370\u0374\u0376\u0377\u037b\u037d\u0388\u038a"
180
+ u"\u038e\u03a1\u03a3\u03f5\u03f7\u0481\u048a\u052f\u0531\u0556\u0560"
181
+ u"\u0588\u05d0\u05ea\u05ef\u05f2\u0620\u064a\u066e\u066f\u0671\u06d3"
182
+ u"\u06e5\u06e6\u06ee\u06ef\u06fa\u06fc\u0712\u072f\u074d\u07a5\u07ca"
183
+ u"\u07ea\u07f4\u07f5\u0800\u0815\u0840\u0858\u0860\u086a\u0870\u0887"
184
+ u"\u0889\u088e\u08a0\u08c9\u0904\u0939\u0958\u0961\u0971\u0980\u0985"
185
+ u"\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b6\u09b9\u09dc\u09dd"
186
+ u"\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a"
187
+ u"\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c\u0a72\u0a74"
188
+ u"\u0a85\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5"
189
+ u"\u0ab9\u0ae0\u0ae1\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30"
190
+ u"\u0b32\u0b33\u0b35\u0b39\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e"
191
+ u"\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa"
192
+ u"\u0bae\u0bb9\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c39\u0c58"
193
+ u"\u0c5a\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3"
194
+ u"\u0cb5\u0cb9\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04\u0d0c\u0d0e"
195
+ u"\u0d10\u0d12\u0d3a\u0d54\u0d56\u0d5f\u0d61\u0d7a\u0d7f\u0d85\u0d96"
196
+ u"\u0d9a\u0db1\u0db3\u0dbb\u0dc0\u0dc6\u0e01\u0e30\u0e40\u0e46\u0e81"
197
+ u"\u0e82\u0e86\u0e8a\u0e8c\u0ea3\u0ea7\u0eb0\u0ec0\u0ec4\u0edc\u0edf"
198
+ u"\u0f40\u0f47\u0f49\u0f6c\u0f88\u0f8c\u1000\u102a\u1050\u1055\u105a"
199
+ u"\u105d\u1065\u1066\u106e\u1070\u1075\u1081\u10a0\u10c5\u10d0\u10fa"
200
+ u"\u10fc\u1248\u124a\u124d\u1250\u1256\u125a\u125d\u1260\u1288\u128a"
201
+ u"\u128d\u1290\u12b0\u12b2\u12b5\u12b8\u12be\u12c2\u12c5\u12c8\u12d6"
202
+ u"\u12d8\u1310\u1312\u1315\u1318\u135a\u1380\u138f\u13a0\u13f5\u13f8"
203
+ u"\u13fd\u1401\u166c\u166f\u167f\u1681\u169a\u16a0\u16ea\u16ee\u16f8"
204
+ u"\u1700\u1711\u171f\u1731\u1740\u1751\u1760\u176c\u176e\u1770\u1780"
205
+ u"\u17b3\u1820\u1878\u1880\u18a8\u18b0\u18f5\u1900\u191e\u1950\u196d"
206
+ u"\u1970\u1974\u1980\u19ab\u19b0\u19c9\u1a00\u1a16\u1a20\u1a54\u1b05"
207
+ u"\u1b33\u1b45\u1b4c\u1b83\u1ba0\u1bae\u1baf\u1bba\u1be5\u1c00\u1c23"
208
+ u"\u1c4d\u1c4f\u1c5a\u1c7d\u1c80\u1c88\u1c90\u1cba\u1cbd\u1cbf\u1ce9"
209
+ u"\u1cec\u1cee\u1cf3\u1cf5\u1cf6\u1d00\u1dbf\u1e00\u1f15\u1f18\u1f1d"
210
+ u"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f5f\u1f7d\u1f80\u1fb4\u1fb6"
211
+ u"\u1fbc\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec"
212
+ u"\u1ff2\u1ff4\u1ff6\u1ffc\u2090\u209c\u210a\u2113\u2118\u211d\u212a"
213
+ u"\u2139\u213c\u213f\u2145\u2149\u2160\u2188\u2c00\u2ce4\u2ceb\u2cee"
214
+ u"\u2cf2\u2cf3\u2d00\u2d25\u2d30\u2d67\u2d80\u2d96\u2da0\u2da6\u2da8"
215
+ u"\u2dae\u2db0\u2db6\u2db8\u2dbe\u2dc0\u2dc6\u2dc8\u2dce\u2dd0\u2dd6"
216
+ u"\u2dd8\u2dde\u3005\u3007\u3021\u3029\u3031\u3035\u3038\u303c\u3041"
217
+ u"\u3096\u309d\u309f\u30a1\u30fa\u30fc\u30ff\u3105\u312f\u3131\u318e"
218
+ u"\u31a0\u31bf\u31f0\u31ff\u3400\u4dbf\u4e00\ua48c\ua4d0\ua4fd\ua500"
219
+ u"\ua60c\ua610\ua61f\ua62a\ua62b\ua640\ua66e\ua67f\ua69d\ua6a0\ua6ef"
220
+ u"\ua717\ua71f\ua722\ua788\ua78b\ua7ca\ua7d0\ua7d1\ua7d5\ua7d9\ua7f2"
221
+ u"\ua801\ua803\ua805\ua807\ua80a\ua80c\ua822\ua840\ua873\ua882\ua8b3"
222
+ u"\ua8f2\ua8f7\ua8fd\ua8fe\ua90a\ua925\ua930\ua946\ua960\ua97c\ua984"
223
+ u"\ua9b2\ua9e0\ua9e4\ua9e6\ua9ef\ua9fa\ua9fe\uaa00\uaa28\uaa40\uaa42"
224
+ u"\uaa44\uaa4b\uaa60\uaa76\uaa7e\uaaaf\uaab5\uaab6\uaab9\uaabd\uaadb"
225
+ u"\uaadd\uaae0\uaaea\uaaf2\uaaf4\uab01\uab06\uab09\uab0e\uab11\uab16"
226
+ u"\uab20\uab26\uab28\uab2e\uab30\uab5a\uab5c\uab69\uab70\uabe2\uac00"
227
+ u"\ud7a3\ud7b0\ud7c6\ud7cb\ud7fb\uf900\ufa6d\ufa70\ufad9\ufb00\ufb06"
228
+ u"\ufb13\ufb17\ufb1f\ufb28\ufb2a\ufb36\ufb38\ufb3c\ufb40\ufb41\ufb43"
229
+ u"\ufb44\ufb46\ufbb1\ufbd3\ufc5d\ufc64\ufd3d\ufd50\ufd8f\ufd92\ufdc7"
230
+ u"\ufdf0\ufdf9\ufe7f\ufefc\uff21\uff3a\uff41\uff5a\uff66\uff9d\uffa0"
231
+ u"\uffbe\uffc2\uffc7\uffca\uffcf\uffd2\uffd7\uffda\uffdc\U00010000\U0001000b"
232
+ u"\U0001000d\U00010026\U00010028\U0001003a\U0001003c\U0001003d\U0001003f\U0001004d\U00010050\U0001005d\U00010080"
233
+ u"\U000100fa\U00010140\U00010174\U00010280\U0001029c\U000102a0\U000102d0\U00010300\U0001031f\U0001032d\U0001034a"
234
+ u"\U00010350\U00010375\U00010380\U0001039d\U000103a0\U000103c3\U000103c8\U000103cf\U000103d1\U000103d5\U00010400"
235
+ u"\U0001049d\U000104b0\U000104d3\U000104d8\U000104fb\U00010500\U00010527\U00010530\U00010563\U00010570\U0001057a"
236
+ u"\U0001057c\U0001058a\U0001058c\U00010592\U00010594\U00010595\U00010597\U000105a1\U000105a3\U000105b1\U000105b3"
237
+ u"\U000105b9\U000105bb\U000105bc\U00010600\U00010736\U00010740\U00010755\U00010760\U00010767\U00010780\U00010785"
238
+ u"\U00010787\U000107b0\U000107b2\U000107ba\U00010800\U00010805\U0001080a\U00010835\U00010837\U00010838\U0001083f"
239
+ u"\U00010855\U00010860\U00010876\U00010880\U0001089e\U000108e0\U000108f2\U000108f4\U000108f5\U00010900\U00010915"
240
+ u"\U00010920\U00010939\U00010980\U000109b7\U000109be\U000109bf\U00010a10\U00010a13\U00010a15\U00010a17\U00010a19"
241
+ u"\U00010a35\U00010a60\U00010a7c\U00010a80\U00010a9c\U00010ac0\U00010ac7\U00010ac9\U00010ae4\U00010b00\U00010b35"
242
+ u"\U00010b40\U00010b55\U00010b60\U00010b72\U00010b80\U00010b91\U00010c00\U00010c48\U00010c80\U00010cb2\U00010cc0"
243
+ u"\U00010cf2\U00010d00\U00010d23\U00010e80\U00010ea9\U00010eb0\U00010eb1\U00010f00\U00010f1c\U00010f30\U00010f45"
244
+ u"\U00010f70\U00010f81\U00010fb0\U00010fc4\U00010fe0\U00010ff6\U00011003\U00011037\U00011071\U00011072\U00011083"
245
+ u"\U000110af\U000110d0\U000110e8\U00011103\U00011126\U00011150\U00011172\U00011183\U000111b2\U000111c1\U000111c4"
246
+ u"\U00011200\U00011211\U00011213\U0001122b\U0001123f\U00011240\U00011280\U00011286\U0001128a\U0001128d\U0001128f"
247
+ u"\U0001129d\U0001129f\U000112a8\U000112b0\U000112de\U00011305\U0001130c\U0001130f\U00011310\U00011313\U00011328"
248
+ u"\U0001132a\U00011330\U00011332\U00011333\U00011335\U00011339\U0001135d\U00011361\U00011400\U00011434\U00011447"
249
+ u"\U0001144a\U0001145f\U00011461\U00011480\U000114af\U000114c4\U000114c5\U00011580\U000115ae\U000115d8\U000115db"
250
+ u"\U00011600\U0001162f\U00011680\U000116aa\U00011700\U0001171a\U00011740\U00011746\U00011800\U0001182b\U000118a0"
251
+ u"\U000118df\U000118ff\U00011906\U0001190c\U00011913\U00011915\U00011916\U00011918\U0001192f\U000119a0\U000119a7"
252
+ u"\U000119aa\U000119d0\U00011a0b\U00011a32\U00011a5c\U00011a89\U00011ab0\U00011af8\U00011c00\U00011c08\U00011c0a"
253
+ u"\U00011c2e\U00011c72\U00011c8f\U00011d00\U00011d06\U00011d08\U00011d09\U00011d0b\U00011d30\U00011d60\U00011d65"
254
+ u"\U00011d67\U00011d68\U00011d6a\U00011d89\U00011ee0\U00011ef2\U00011f04\U00011f10\U00011f12\U00011f33\U00012000"
255
+ u"\U00012399\U00012400\U0001246e\U00012480\U00012543\U00012f90\U00012ff0\U00013000\U0001342f\U00013441\U00013446"
256
+ u"\U00014400\U00014646\U00016800\U00016a38\U00016a40\U00016a5e\U00016a70\U00016abe\U00016ad0\U00016aed\U00016b00"
257
+ u"\U00016b2f\U00016b40\U00016b43\U00016b63\U00016b77\U00016b7d\U00016b8f\U00016e40\U00016e7f\U00016f00\U00016f4a"
258
+ u"\U00016f93\U00016f9f\U00016fe0\U00016fe1\U00017000\U000187f7\U00018800\U00018cd5\U00018d00\U00018d08\U0001aff0"
259
+ u"\U0001aff3\U0001aff5\U0001affb\U0001affd\U0001affe\U0001b000\U0001b122\U0001b150\U0001b152\U0001b164\U0001b167"
260
+ u"\U0001b170\U0001b2fb\U0001bc00\U0001bc6a\U0001bc70\U0001bc7c\U0001bc80\U0001bc88\U0001bc90\U0001bc99\U0001d400"
261
+ u"\U0001d454\U0001d456\U0001d49c\U0001d49e\U0001d49f\U0001d4a5\U0001d4a6\U0001d4a9\U0001d4ac\U0001d4ae\U0001d4b9"
262
+ u"\U0001d4bd\U0001d4c3\U0001d4c5\U0001d505\U0001d507\U0001d50a\U0001d50d\U0001d514\U0001d516\U0001d51c\U0001d51e"
263
+ u"\U0001d539\U0001d53b\U0001d53e\U0001d540\U0001d544\U0001d54a\U0001d550\U0001d552\U0001d6a5\U0001d6a8\U0001d6c0"
264
+ u"\U0001d6c2\U0001d6da\U0001d6dc\U0001d6fa\U0001d6fc\U0001d714\U0001d716\U0001d734\U0001d736\U0001d74e\U0001d750"
265
+ u"\U0001d76e\U0001d770\U0001d788\U0001d78a\U0001d7a8\U0001d7aa\U0001d7c2\U0001d7c4\U0001d7cb\U0001df00\U0001df1e"
266
+ u"\U0001df25\U0001df2a\U0001e030\U0001e06d\U0001e100\U0001e12c\U0001e137\U0001e13d\U0001e290\U0001e2ad\U0001e2c0"
267
+ u"\U0001e2eb\U0001e4d0\U0001e4eb\U0001e7e0\U0001e7e6\U0001e7e8\U0001e7eb\U0001e7ed\U0001e7ee\U0001e7f0\U0001e7fe"
268
+ u"\U0001e800\U0001e8c4\U0001e900\U0001e943\U0001ee00\U0001ee03\U0001ee05\U0001ee1f\U0001ee21\U0001ee22\U0001ee29"
269
+ u"\U0001ee32\U0001ee34\U0001ee37\U0001ee4d\U0001ee4f\U0001ee51\U0001ee52\U0001ee61\U0001ee62\U0001ee67\U0001ee6a"
270
+ u"\U0001ee6c\U0001ee72\U0001ee74\U0001ee77\U0001ee79\U0001ee7c\U0001ee80\U0001ee89\U0001ee8b\U0001ee9b\U0001eea1"
271
+ u"\U0001eea3\U0001eea5\U0001eea9\U0001eeab\U0001eebb\U00020000\U0002a6df\U0002a700\U0002b739\U0002b740\U0002b81d"
272
+ u"\U0002b820\U0002cea1\U0002ceb0\U0002ebe0\U0002f800\U0002fa1d\U00030000\U0003134a"
273
+ )
274
+ unicode_continuation_ch_any = (
275
+ u"\u00b7\u0387\u05bf\u05c7\u0670\u0711\u07fd\u09bc\u09d7\u09fe\u0a3c"
276
+ u"\u0a51\u0a75\u0abc\u0b3c\u0b82\u0bd7\u0c3c\u0cbc\u0cf3\u0d57\u0dca"
277
+ u"\u0dd6\u0e31\u0eb1\u0f35\u0f37\u0f39\u0fc6\u17dd\u18a9\u1ced\u1cf4"
278
+ u"\u2054\u20e1\u2d7f\ua66f\ua802\ua806\ua80b\ua82c\ua9e5\uaa43\uaab0"
279
+ u"\uaac1\ufb1e\uff3f\U000101fd\U000102e0\U00010a3f\U000110c2\U00011173\U0001123e\U00011241\U00011357"
280
+ u"\U0001145e\U00011940\U000119e4\U00011a47\U00011d3a\U00011d47\U00011f03\U00013440\U00016f4f\U00016fe4\U0001da75"
281
+ u"\U0001da84\U0001e08f\U0001e2ae"
282
+ )
283
+ unicode_continuation_ch_range = (
284
+ u"\u0030\u0039\u0300\u036f\u0483\u0487\u0591\u05bd\u05c1\u05c2\u05c4"
285
+ u"\u05c5\u0610\u061a\u064b\u0669\u06d6\u06dc\u06df\u06e4\u06e7\u06e8"
286
+ u"\u06ea\u06ed\u06f0\u06f9\u0730\u074a\u07a6\u07b0\u07c0\u07c9\u07eb"
287
+ u"\u07f3\u0816\u0819\u081b\u0823\u0825\u0827\u0829\u082d\u0859\u085b"
288
+ u"\u0898\u089f\u08ca\u08e1\u08e3\u0903\u093a\u093c\u093e\u094f\u0951"
289
+ u"\u0957\u0962\u0963\u0966\u096f\u0981\u0983\u09be\u09c4\u09c7\u09c8"
290
+ u"\u09cb\u09cd\u09e2\u09e3\u09e6\u09ef\u0a01\u0a03\u0a3e\u0a42\u0a47"
291
+ u"\u0a48\u0a4b\u0a4d\u0a66\u0a71\u0a81\u0a83\u0abe\u0ac5\u0ac7\u0ac9"
292
+ u"\u0acb\u0acd\u0ae2\u0ae3\u0ae6\u0aef\u0afa\u0aff\u0b01\u0b03\u0b3e"
293
+ u"\u0b44\u0b47\u0b48\u0b4b\u0b4d\u0b55\u0b57\u0b62\u0b63\u0b66\u0b6f"
294
+ u"\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd\u0be6\u0bef\u0c00\u0c04\u0c3e"
295
+ u"\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66\u0c6f"
296
+ u"\u0c81\u0c83\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6\u0ce2"
297
+ u"\u0ce3\u0ce6\u0cef\u0d00\u0d03\u0d3b\u0d3c\u0d3e\u0d44\u0d46\u0d48"
298
+ u"\u0d4a\u0d4d\u0d62\u0d63\u0d66\u0d6f\u0d81\u0d83\u0dcf\u0dd4\u0dd8"
299
+ u"\u0ddf\u0de6\u0def\u0df2\u0df3\u0e33\u0e3a\u0e47\u0e4e\u0e50\u0e59"
300
+ u"\u0eb3\u0ebc\u0ec8\u0ece\u0ed0\u0ed9\u0f18\u0f19\u0f20\u0f29\u0f3e"
301
+ u"\u0f3f\u0f71\u0f84\u0f86\u0f87\u0f8d\u0f97\u0f99\u0fbc\u102b\u103e"
302
+ u"\u1040\u1049\u1056\u1059\u105e\u1060\u1062\u1064\u1067\u106d\u1071"
303
+ u"\u1074\u1082\u108d\u108f\u109d\u135d\u135f\u1369\u1371\u1712\u1715"
304
+ u"\u1732\u1734\u1752\u1753\u1772\u1773\u17b4\u17d3\u17e0\u17e9\u180b"
305
+ u"\u180d\u180f\u1819\u1920\u192b\u1930\u193b\u1946\u194f\u19d0\u19da"
306
+ u"\u1a17\u1a1b\u1a55\u1a5e\u1a60\u1a7c\u1a7f\u1a89\u1a90\u1a99\u1ab0"
307
+ u"\u1abd\u1abf\u1ace\u1b00\u1b04\u1b34\u1b44\u1b50\u1b59\u1b6b\u1b73"
308
+ u"\u1b80\u1b82\u1ba1\u1bad\u1bb0\u1bb9\u1be6\u1bf3\u1c24\u1c37\u1c40"
309
+ u"\u1c49\u1c50\u1c59\u1cd0\u1cd2\u1cd4\u1ce8\u1cf7\u1cf9\u1dc0\u1dff"
310
+ u"\u203f\u2040\u20d0\u20dc\u20e5\u20f0\u2cef\u2cf1\u2de0\u2dff\u302a"
311
+ u"\u302f\u3099\u309a\ua620\ua629\ua674\ua67d\ua69e\ua69f\ua6f0\ua6f1"
312
+ u"\ua823\ua827\ua880\ua881\ua8b4\ua8c5\ua8d0\ua8d9\ua8e0\ua8f1\ua8ff"
313
+ u"\ua909\ua926\ua92d\ua947\ua953\ua980\ua983\ua9b3\ua9c0\ua9d0\ua9d9"
314
+ u"\ua9f0\ua9f9\uaa29\uaa36\uaa4c\uaa4d\uaa50\uaa59\uaa7b\uaa7d\uaab2"
315
+ u"\uaab4\uaab7\uaab8\uaabe\uaabf\uaaeb\uaaef\uaaf5\uaaf6\uabe3\uabea"
316
+ u"\uabec\uabed\uabf0\uabf9\ufe00\ufe0f\ufe20\ufe2f\ufe33\ufe34\ufe4d"
317
+ u"\ufe4f\uff10\uff19\uff9e\uff9f\U00010376\U0001037a\U000104a0\U000104a9\U00010a01\U00010a03"
318
+ u"\U00010a05\U00010a06\U00010a0c\U00010a0f\U00010a38\U00010a3a\U00010ae5\U00010ae6\U00010d24\U00010d27\U00010d30"
319
+ u"\U00010d39\U00010eab\U00010eac\U00010efd\U00010eff\U00010f46\U00010f50\U00010f82\U00010f85\U00011000\U00011002"
320
+ u"\U00011038\U00011046\U00011066\U00011070\U00011073\U00011074\U0001107f\U00011082\U000110b0\U000110ba\U000110f0"
321
+ u"\U000110f9\U00011100\U00011102\U00011127\U00011134\U00011136\U0001113f\U00011145\U00011146\U00011180\U00011182"
322
+ u"\U000111b3\U000111c0\U000111c9\U000111cc\U000111ce\U000111d9\U0001122c\U00011237\U000112df\U000112ea\U000112f0"
323
+ u"\U000112f9\U00011300\U00011303\U0001133b\U0001133c\U0001133e\U00011344\U00011347\U00011348\U0001134b\U0001134d"
324
+ u"\U00011362\U00011363\U00011366\U0001136c\U00011370\U00011374\U00011435\U00011446\U00011450\U00011459\U000114b0"
325
+ u"\U000114c3\U000114d0\U000114d9\U000115af\U000115b5\U000115b8\U000115c0\U000115dc\U000115dd\U00011630\U00011640"
326
+ u"\U00011650\U00011659\U000116ab\U000116b7\U000116c0\U000116c9\U0001171d\U0001172b\U00011730\U00011739\U0001182c"
327
+ u"\U0001183a\U000118e0\U000118e9\U00011930\U00011935\U00011937\U00011938\U0001193b\U0001193e\U00011942\U00011943"
328
+ u"\U00011950\U00011959\U000119d1\U000119d7\U000119da\U000119e0\U00011a01\U00011a0a\U00011a33\U00011a39\U00011a3b"
329
+ u"\U00011a3e\U00011a51\U00011a5b\U00011a8a\U00011a99\U00011c2f\U00011c36\U00011c38\U00011c3f\U00011c50\U00011c59"
330
+ u"\U00011c92\U00011ca7\U00011ca9\U00011cb6\U00011d31\U00011d36\U00011d3c\U00011d3d\U00011d3f\U00011d45\U00011d50"
331
+ u"\U00011d59\U00011d8a\U00011d8e\U00011d90\U00011d91\U00011d93\U00011d97\U00011da0\U00011da9\U00011ef3\U00011ef6"
332
+ u"\U00011f00\U00011f01\U00011f34\U00011f3a\U00011f3e\U00011f42\U00011f50\U00011f59\U00013447\U00013455\U00016a60"
333
+ u"\U00016a69\U00016ac0\U00016ac9\U00016af0\U00016af4\U00016b30\U00016b36\U00016b50\U00016b59\U00016f51\U00016f87"
334
+ u"\U00016f8f\U00016f92\U00016ff0\U00016ff1\U0001bc9d\U0001bc9e\U0001cf00\U0001cf2d\U0001cf30\U0001cf46\U0001d165"
335
+ u"\U0001d169\U0001d16d\U0001d172\U0001d17b\U0001d182\U0001d185\U0001d18b\U0001d1aa\U0001d1ad\U0001d242\U0001d244"
336
+ u"\U0001d7ce\U0001d7ff\U0001da00\U0001da36\U0001da3b\U0001da6c\U0001da9b\U0001da9f\U0001daa1\U0001daaf\U0001e000"
337
+ u"\U0001e006\U0001e008\U0001e018\U0001e01b\U0001e021\U0001e023\U0001e024\U0001e026\U0001e02a\U0001e130\U0001e136"
338
+ u"\U0001e140\U0001e149\U0001e2ec\U0001e2f9\U0001e4ec\U0001e4f9\U0001e8d0\U0001e8d6\U0001e944\U0001e94a\U0001e950"
339
+ u"\U0001e959\U0001fbf0\U0001fbf9"
340
+ )
341
+
342
+ # END GENERATED CODE
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/MemoryView.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from .Errors import CompileError, error
4
+ from . import ExprNodes
5
+ from .ExprNodes import IntNode, NameNode, AttributeNode
6
+ from . import Options
7
+ from .Code import UtilityCode, TempitaUtilityCode
8
+ from .UtilityCode import CythonUtilityCode
9
+ from . import Buffer
10
+ from . import PyrexTypes
11
+ from . import ModuleNode
12
+
13
+ START_ERR = "Start must not be given."
14
+ STOP_ERR = "Axis specification only allowed in the 'step' slot."
15
+ STEP_ERR = "Step must be omitted, 1, or a valid specifier."
16
+ BOTH_CF_ERR = "Cannot specify an array that is both C and Fortran contiguous."
17
+ INVALID_ERR = "Invalid axis specification."
18
+ NOT_CIMPORTED_ERR = "Variable was not cimported from cython.view"
19
+ EXPR_ERR = "no expressions allowed in axis spec, only names and literals."
20
+ CF_ERR = "Invalid axis specification for a C/Fortran contiguous array."
21
+ ERR_UNINITIALIZED = ("Cannot check if memoryview %s is initialized without the "
22
+ "GIL, consider using initializedcheck(False)")
23
+
24
+
25
+ format_flag = "PyBUF_FORMAT"
26
+
27
+ memview_c_contiguous = "(PyBUF_C_CONTIGUOUS | PyBUF_FORMAT)"
28
+ memview_f_contiguous = "(PyBUF_F_CONTIGUOUS | PyBUF_FORMAT)"
29
+ memview_any_contiguous = "(PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT)"
30
+ memview_full_access = "PyBUF_FULL_RO"
31
+ #memview_strided_access = "PyBUF_STRIDED_RO"
32
+ memview_strided_access = "PyBUF_RECORDS_RO"
33
+
34
+ MEMVIEW_DIRECT = '__Pyx_MEMVIEW_DIRECT'
35
+ MEMVIEW_PTR = '__Pyx_MEMVIEW_PTR'
36
+ MEMVIEW_FULL = '__Pyx_MEMVIEW_FULL'
37
+ MEMVIEW_CONTIG = '__Pyx_MEMVIEW_CONTIG'
38
+ MEMVIEW_STRIDED= '__Pyx_MEMVIEW_STRIDED'
39
+ MEMVIEW_FOLLOW = '__Pyx_MEMVIEW_FOLLOW'
40
+
41
+ _spec_to_const = {
42
+ 'direct' : MEMVIEW_DIRECT,
43
+ 'ptr' : MEMVIEW_PTR,
44
+ 'full' : MEMVIEW_FULL,
45
+ 'contig' : MEMVIEW_CONTIG,
46
+ 'strided': MEMVIEW_STRIDED,
47
+ 'follow' : MEMVIEW_FOLLOW,
48
+ }
49
+
50
+ _spec_to_abbrev = {
51
+ 'direct' : 'd',
52
+ 'ptr' : 'p',
53
+ 'full' : 'f',
54
+ 'contig' : 'c',
55
+ 'strided' : 's',
56
+ 'follow' : '_',
57
+ }
58
+
59
+ memslice_entry_init = "{ 0, 0, { 0 }, { 0 }, { 0 } }"
60
+
61
+ memview_name = u'memoryview'
62
+ memview_typeptr_cname = '__pyx_memoryview_type'
63
+ memview_objstruct_cname = '__pyx_memoryview_obj'
64
+ memviewslice_cname = u'__Pyx_memviewslice'
65
+
66
+
67
+ def put_init_entry(mv_cname, code):
68
+ code.putln("%s.data = NULL;" % mv_cname)
69
+ code.putln("%s.memview = NULL;" % mv_cname)
70
+
71
+
72
+ #def axes_to_str(axes):
73
+ # return "".join([access[0].upper()+packing[0] for (access, packing) in axes])
74
+
75
+
76
+ def put_acquire_memoryviewslice(lhs_cname, lhs_type, lhs_pos, rhs, code,
77
+ have_gil=False, first_assignment=True):
78
+ "We can avoid decreffing the lhs if we know it is the first assignment"
79
+ assert rhs.type.is_memoryviewslice
80
+
81
+ pretty_rhs = rhs.result_in_temp() or rhs.is_simple()
82
+ if pretty_rhs:
83
+ rhstmp = rhs.result()
84
+ else:
85
+ rhstmp = code.funcstate.allocate_temp(lhs_type, manage_ref=False)
86
+ code.putln("%s = %s;" % (rhstmp, rhs.result_as(lhs_type)))
87
+
88
+ # Allow uninitialized assignment
89
+ #code.putln(code.put_error_if_unbound(lhs_pos, rhs.entry))
90
+ put_assign_to_memviewslice(lhs_cname, rhs, rhstmp, lhs_type, code,
91
+ have_gil=have_gil, first_assignment=first_assignment)
92
+
93
+ if not pretty_rhs:
94
+ code.funcstate.release_temp(rhstmp)
95
+
96
+
97
+ def put_assign_to_memviewslice(lhs_cname, rhs, rhs_cname, memviewslicetype, code,
98
+ have_gil=False, first_assignment=False):
99
+ if lhs_cname == rhs_cname:
100
+ # self assignment is tricky because memoryview xdecref clears the memoryview
101
+ # thus invalidating both sides of the assignment. Therefore make it actually do nothing
102
+ code.putln("/* memoryview self assignment no-op */")
103
+ return
104
+
105
+ if not first_assignment:
106
+ code.put_xdecref(lhs_cname, memviewslicetype,
107
+ have_gil=have_gil)
108
+
109
+ if not rhs.result_in_temp():
110
+ rhs.make_owned_memoryviewslice(code)
111
+
112
+ code.putln("%s = %s;" % (lhs_cname, rhs_cname))
113
+
114
+
115
+ def get_buf_flags(specs):
116
+ is_c_contig, is_f_contig = is_cf_contig(specs)
117
+
118
+ if is_c_contig:
119
+ return memview_c_contiguous
120
+ elif is_f_contig:
121
+ return memview_f_contiguous
122
+
123
+ access, packing = zip(*specs)
124
+
125
+ if 'full' in access or 'ptr' in access:
126
+ return memview_full_access
127
+ else:
128
+ return memview_strided_access
129
+
130
+
131
+ def insert_newaxes(memoryviewtype, n):
132
+ axes = [('direct', 'strided')] * n
133
+ axes.extend(memoryviewtype.axes)
134
+ return PyrexTypes.MemoryViewSliceType(memoryviewtype.dtype, axes)
135
+
136
+
137
+ def broadcast_types(src, dst):
138
+ n = abs(src.ndim - dst.ndim)
139
+ if src.ndim < dst.ndim:
140
+ return insert_newaxes(src, n), dst
141
+ else:
142
+ return src, insert_newaxes(dst, n)
143
+
144
+
145
+ def valid_memslice_dtype(dtype, i=0):
146
+ """
147
+ Return whether type dtype can be used as the base type of a
148
+ memoryview slice.
149
+
150
+ We support structs, numeric types and objects
151
+ """
152
+ if dtype.is_complex and dtype.real_type.is_int:
153
+ return False
154
+
155
+ if dtype is PyrexTypes.c_bint_type:
156
+ return False
157
+
158
+ if dtype.is_struct and dtype.kind == 'struct':
159
+ for member in dtype.scope.var_entries:
160
+ if not valid_memslice_dtype(member.type):
161
+ return False
162
+
163
+ return True
164
+
165
+ return (
166
+ dtype.is_error or
167
+ # Pointers are not valid (yet)
168
+ # (dtype.is_ptr and valid_memslice_dtype(dtype.base_type)) or
169
+ (dtype.is_array and i < 8 and
170
+ valid_memslice_dtype(dtype.base_type, i + 1)) or
171
+ dtype.is_numeric or
172
+ dtype.is_pyobject or
173
+ dtype.is_fused or # accept this as it will be replaced by specializations later
174
+ (dtype.is_typedef and valid_memslice_dtype(dtype.typedef_base_type))
175
+ )
176
+
177
+
178
+ class MemoryViewSliceBufferEntry(Buffer.BufferEntry):
179
+ """
180
+ May be used during code generation time to be queried for
181
+ shape/strides/suboffsets attributes, or to perform indexing or slicing.
182
+ """
183
+ def __init__(self, entry):
184
+ self.entry = entry
185
+ self.type = entry.type
186
+ self.cname = entry.cname
187
+
188
+ self.buf_ptr = "%s.data" % self.cname
189
+
190
+ dtype = self.entry.type.dtype
191
+ self.buf_ptr_type = PyrexTypes.CPtrType(dtype)
192
+ self.init_attributes()
193
+
194
+ def get_buf_suboffsetvars(self):
195
+ return self._for_all_ndim("%s.suboffsets[%d]")
196
+
197
+ def get_buf_stridevars(self):
198
+ return self._for_all_ndim("%s.strides[%d]")
199
+
200
+ def get_buf_shapevars(self):
201
+ return self._for_all_ndim("%s.shape[%d]")
202
+
203
+ def generate_buffer_lookup_code(self, code, index_cnames):
204
+ axes = [(dim, index_cnames[dim], access, packing)
205
+ for dim, (access, packing) in enumerate(self.type.axes)]
206
+ return self._generate_buffer_lookup_code(code, axes)
207
+
208
+ def _generate_buffer_lookup_code(self, code, axes, cast_result=True):
209
+ """
210
+ Generate a single expression that indexes the memory view slice
211
+ in each dimension.
212
+ """
213
+ bufp = self.buf_ptr
214
+ type_decl = self.type.dtype.empty_declaration_code()
215
+
216
+ for dim, index, access, packing in axes:
217
+ shape = "%s.shape[%d]" % (self.cname, dim)
218
+ stride = "%s.strides[%d]" % (self.cname, dim)
219
+ suboffset = "%s.suboffsets[%d]" % (self.cname, dim)
220
+
221
+ flag = get_memoryview_flag(access, packing)
222
+
223
+ if flag in ("generic", "generic_contiguous"):
224
+ # Note: we cannot do cast tricks to avoid stride multiplication
225
+ # for generic_contiguous, as we may have to do (dtype *)
226
+ # or (dtype **) arithmetic, we won't know which unless
227
+ # we check suboffsets
228
+ code.globalstate.use_utility_code(memviewslice_index_helpers)
229
+ bufp = ('__pyx_memviewslice_index_full(%s, %s, %s, %s)' %
230
+ (bufp, index, stride, suboffset))
231
+
232
+ elif flag == "indirect":
233
+ bufp = "(%s + %s * %s)" % (bufp, index, stride)
234
+ bufp = ("(*((char **) %s) + %s)" % (bufp, suboffset))
235
+
236
+ elif flag == "indirect_contiguous":
237
+ # Note: we do char ** arithmetic
238
+ bufp = "(*((char **) %s + %s) + %s)" % (bufp, index, suboffset)
239
+
240
+ elif flag == "strided":
241
+ bufp = "(%s + %s * %s)" % (bufp, index, stride)
242
+
243
+ else:
244
+ assert flag == 'contiguous', flag
245
+ bufp = '((char *) (((%s *) %s) + %s))' % (type_decl, bufp, index)
246
+
247
+ bufp = '( /* dim=%d */ %s )' % (dim, bufp)
248
+
249
+ if cast_result:
250
+ return "((%s *) %s)" % (type_decl, bufp)
251
+
252
+ return bufp
253
+
254
+ def generate_buffer_slice_code(self, code, indices, dst, dst_type, have_gil,
255
+ have_slices, directives):
256
+ """
257
+ Slice a memoryviewslice.
258
+
259
+ indices - list of index nodes. If not a SliceNode, or NoneNode,
260
+ then it must be coercible to Py_ssize_t
261
+
262
+ Simply call __pyx_memoryview_slice_memviewslice with the right
263
+ arguments, unless the dimension is omitted or a bare ':', in which
264
+ case we copy over the shape/strides/suboffsets attributes directly
265
+ for that dimension.
266
+ """
267
+ src = self.cname
268
+
269
+ code.putln("%(dst)s.data = %(src)s.data;" % locals())
270
+ code.putln("%(dst)s.memview = %(src)s.memview;" % locals())
271
+ code.put_incref_memoryviewslice(dst, dst_type, have_gil=have_gil)
272
+
273
+ all_dimensions_direct = all(access == 'direct' for access, packing in self.type.axes)
274
+ suboffset_dim_temp = []
275
+
276
+ def get_suboffset_dim():
277
+ # create global temp variable at request
278
+ if not suboffset_dim_temp:
279
+ suboffset_dim = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
280
+ code.putln("%s = -1;" % suboffset_dim)
281
+ suboffset_dim_temp.append(suboffset_dim)
282
+ return suboffset_dim_temp[0]
283
+
284
+ dim = -1
285
+ new_ndim = 0
286
+ for index in indices:
287
+ if index.is_none:
288
+ # newaxis
289
+ for attrib, value in [('shape', 1), ('strides', 0), ('suboffsets', -1)]:
290
+ code.putln("%s.%s[%d] = %d;" % (dst, attrib, new_ndim, value))
291
+
292
+ new_ndim += 1
293
+ continue
294
+
295
+ dim += 1
296
+ access, packing = self.type.axes[dim]
297
+
298
+ if index.is_slice:
299
+ # slice, unspecified dimension, or part of ellipsis
300
+ d = dict(locals())
301
+ for s in "start stop step".split():
302
+ idx = getattr(index, s)
303
+ have_idx = d['have_' + s] = not idx.is_none
304
+ d[s] = idx.result() if have_idx else "0"
305
+
306
+ if not (d['have_start'] or d['have_stop'] or d['have_step']):
307
+ # full slice (:), simply copy over the extent, stride
308
+ # and suboffset. Also update suboffset_dim if needed
309
+ d['access'] = access
310
+ util_name = "SimpleSlice"
311
+ else:
312
+ util_name = "ToughSlice"
313
+ d['error_goto'] = code.error_goto(index.pos)
314
+
315
+ new_ndim += 1
316
+ else:
317
+ # normal index
318
+ idx = index.result()
319
+
320
+ indirect = access != 'direct'
321
+ if indirect:
322
+ generic = access == 'full'
323
+ if new_ndim != 0:
324
+ return error(index.pos,
325
+ "All preceding dimensions must be "
326
+ "indexed and not sliced")
327
+
328
+ d = dict(
329
+ locals(),
330
+ wraparound=int(directives['wraparound']),
331
+ boundscheck=int(directives['boundscheck']),
332
+ )
333
+ if d['boundscheck']:
334
+ d['error_goto'] = code.error_goto(index.pos)
335
+ util_name = "SliceIndex"
336
+
337
+ _, impl = TempitaUtilityCode.load_as_string(util_name, "MemoryView_C.c", context=d)
338
+ code.put(impl)
339
+
340
+ if suboffset_dim_temp:
341
+ code.funcstate.release_temp(suboffset_dim_temp[0])
342
+
343
+
344
+ def empty_slice(pos):
345
+ none = ExprNodes.NoneNode(pos)
346
+ return ExprNodes.SliceNode(pos, start=none,
347
+ stop=none, step=none)
348
+
349
+
350
+ def unellipsify(indices, ndim):
351
+ result = []
352
+ seen_ellipsis = False
353
+ have_slices = False
354
+
355
+ newaxes = [newaxis for newaxis in indices if newaxis.is_none]
356
+ n_indices = len(indices) - len(newaxes)
357
+
358
+ for index in indices:
359
+ if isinstance(index, ExprNodes.EllipsisNode):
360
+ have_slices = True
361
+ full_slice = empty_slice(index.pos)
362
+
363
+ if seen_ellipsis:
364
+ result.append(full_slice)
365
+ else:
366
+ nslices = ndim - n_indices + 1
367
+ result.extend([full_slice] * nslices)
368
+ seen_ellipsis = True
369
+ else:
370
+ have_slices = have_slices or index.is_slice or index.is_none
371
+ result.append(index)
372
+
373
+ result_length = len(result) - len(newaxes)
374
+ if result_length < ndim:
375
+ have_slices = True
376
+ nslices = ndim - result_length
377
+ result.extend([empty_slice(indices[-1].pos)] * nslices)
378
+
379
+ return have_slices, result, newaxes
380
+
381
+
382
+ def get_memoryview_flag(access, packing):
383
+ if access == 'full' and packing in ('strided', 'follow'):
384
+ return 'generic'
385
+ elif access == 'full' and packing == 'contig':
386
+ return 'generic_contiguous'
387
+ elif access == 'ptr' and packing in ('strided', 'follow'):
388
+ return 'indirect'
389
+ elif access == 'ptr' and packing == 'contig':
390
+ return 'indirect_contiguous'
391
+ elif access == 'direct' and packing in ('strided', 'follow'):
392
+ return 'strided'
393
+ else:
394
+ assert (access, packing) == ('direct', 'contig'), (access, packing)
395
+ return 'contiguous'
396
+
397
+
398
+ def get_is_contig_func_name(contig_type, ndim):
399
+ assert contig_type in ('C', 'F')
400
+ return "__pyx_memviewslice_is_contig_%s%d" % (contig_type, ndim)
401
+
402
+
403
+ def get_is_contig_utility(contig_type, ndim):
404
+ assert contig_type in ('C', 'F')
405
+ C = dict(context, ndim=ndim, contig_type=contig_type)
406
+ utility = load_memview_c_utility("MemviewSliceCheckContig", C, requires=[is_contig_utility])
407
+ return utility
408
+
409
+
410
+ def slice_iter(slice_type, slice_result, ndim, code, force_strided=False):
411
+ if (slice_type.is_c_contig or slice_type.is_f_contig) and not force_strided:
412
+ return ContigSliceIter(slice_type, slice_result, ndim, code)
413
+ else:
414
+ return StridedSliceIter(slice_type, slice_result, ndim, code)
415
+
416
+
417
+ class SliceIter(object):
418
+ def __init__(self, slice_type, slice_result, ndim, code):
419
+ self.slice_type = slice_type
420
+ self.slice_result = slice_result
421
+ self.code = code
422
+ self.ndim = ndim
423
+
424
+
425
+ class ContigSliceIter(SliceIter):
426
+ def start_loops(self):
427
+ code = self.code
428
+ code.begin_block()
429
+
430
+ type_decl = self.slice_type.dtype.empty_declaration_code()
431
+
432
+ total_size = ' * '.join("%s.shape[%d]" % (self.slice_result, i)
433
+ for i in range(self.ndim))
434
+ code.putln("Py_ssize_t __pyx_temp_extent = %s;" % total_size)
435
+ code.putln("Py_ssize_t __pyx_temp_idx;")
436
+ code.putln("%s *__pyx_temp_pointer = (%s *) %s.data;" % (
437
+ type_decl, type_decl, self.slice_result))
438
+ code.putln("for (__pyx_temp_idx = 0; "
439
+ "__pyx_temp_idx < __pyx_temp_extent; "
440
+ "__pyx_temp_idx++) {")
441
+
442
+ return "__pyx_temp_pointer"
443
+
444
+ def end_loops(self):
445
+ self.code.putln("__pyx_temp_pointer += 1;")
446
+ self.code.putln("}")
447
+ self.code.end_block()
448
+
449
+
450
+ class StridedSliceIter(SliceIter):
451
+ def start_loops(self):
452
+ code = self.code
453
+ code.begin_block()
454
+
455
+ for i in range(self.ndim):
456
+ t = i, self.slice_result, i
457
+ code.putln("Py_ssize_t __pyx_temp_extent_%d = %s.shape[%d];" % t)
458
+ code.putln("Py_ssize_t __pyx_temp_stride_%d = %s.strides[%d];" % t)
459
+ code.putln("char *__pyx_temp_pointer_%d;" % i)
460
+ code.putln("Py_ssize_t __pyx_temp_idx_%d;" % i)
461
+
462
+ code.putln("__pyx_temp_pointer_0 = %s.data;" % self.slice_result)
463
+
464
+ for i in range(self.ndim):
465
+ if i > 0:
466
+ code.putln("__pyx_temp_pointer_%d = __pyx_temp_pointer_%d;" % (i, i - 1))
467
+
468
+ code.putln("for (__pyx_temp_idx_%d = 0; "
469
+ "__pyx_temp_idx_%d < __pyx_temp_extent_%d; "
470
+ "__pyx_temp_idx_%d++) {" % (i, i, i, i))
471
+
472
+ return "__pyx_temp_pointer_%d" % (self.ndim - 1)
473
+
474
+ def end_loops(self):
475
+ code = self.code
476
+ for i in range(self.ndim - 1, -1, -1):
477
+ code.putln("__pyx_temp_pointer_%d += __pyx_temp_stride_%d;" % (i, i))
478
+ code.putln("}")
479
+
480
+ code.end_block()
481
+
482
+
483
+ def copy_c_or_fortran_cname(memview):
484
+ if memview.is_c_contig:
485
+ c_or_f = 'c'
486
+ else:
487
+ c_or_f = 'f'
488
+
489
+ return "__pyx_memoryview_copy_slice_%s_%s" % (
490
+ memview.specialization_suffix(), c_or_f)
491
+
492
+
493
+ def get_copy_new_utility(pos, from_memview, to_memview):
494
+ if (from_memview.dtype != to_memview.dtype and
495
+ not (from_memview.dtype.is_cv_qualified and from_memview.dtype.cv_base_type == to_memview.dtype)):
496
+ error(pos, "dtypes must be the same!")
497
+ return
498
+ if len(from_memview.axes) != len(to_memview.axes):
499
+ error(pos, "number of dimensions must be same")
500
+ return
501
+ if not (to_memview.is_c_contig or to_memview.is_f_contig):
502
+ error(pos, "to_memview must be c or f contiguous.")
503
+ return
504
+
505
+ for (access, packing) in from_memview.axes:
506
+ if access != 'direct':
507
+ error(pos, "cannot handle 'full' or 'ptr' access at this time.")
508
+ return
509
+
510
+ if to_memview.is_c_contig:
511
+ mode = 'c'
512
+ contig_flag = memview_c_contiguous
513
+ else:
514
+ assert to_memview.is_f_contig
515
+ mode = 'fortran'
516
+ contig_flag = memview_f_contiguous
517
+
518
+ return load_memview_c_utility(
519
+ "CopyContentsUtility",
520
+ context=dict(
521
+ context,
522
+ mode=mode,
523
+ dtype_decl=to_memview.dtype.empty_declaration_code(),
524
+ contig_flag=contig_flag,
525
+ ndim=to_memview.ndim,
526
+ func_cname=copy_c_or_fortran_cname(to_memview),
527
+ dtype_is_object=int(to_memview.dtype.is_pyobject)),
528
+ requires=[copy_contents_new_utility])
529
+
530
+
531
+ def get_axes_specs(env, axes):
532
+ '''
533
+ get_axes_specs(env, axes) -> list of (access, packing) specs for each axis.
534
+ access is one of 'full', 'ptr' or 'direct'
535
+ packing is one of 'contig', 'strided' or 'follow'
536
+ '''
537
+
538
+ cythonscope = env.global_scope().context.cython_scope
539
+ cythonscope.load_cythonscope()
540
+ viewscope = cythonscope.viewscope
541
+
542
+ access_specs = tuple([viewscope.lookup(name)
543
+ for name in ('full', 'direct', 'ptr')])
544
+ packing_specs = tuple([viewscope.lookup(name)
545
+ for name in ('contig', 'strided', 'follow')])
546
+
547
+ is_f_contig, is_c_contig = False, False
548
+ default_access, default_packing = 'direct', 'strided'
549
+ cf_access, cf_packing = default_access, 'follow'
550
+
551
+ axes_specs = []
552
+ # analyse all axes.
553
+ for idx, axis in enumerate(axes):
554
+ if not axis.start.is_none:
555
+ raise CompileError(axis.start.pos, START_ERR)
556
+
557
+ if not axis.stop.is_none:
558
+ raise CompileError(axis.stop.pos, STOP_ERR)
559
+
560
+ if axis.step.is_none:
561
+ axes_specs.append((default_access, default_packing))
562
+
563
+ elif isinstance(axis.step, IntNode):
564
+ # the packing for the ::1 axis is contiguous,
565
+ # all others are cf_packing.
566
+ if axis.step.compile_time_value(env) != 1:
567
+ raise CompileError(axis.step.pos, STEP_ERR)
568
+
569
+ axes_specs.append((cf_access, 'cfcontig'))
570
+
571
+ elif isinstance(axis.step, (NameNode, AttributeNode)):
572
+ entry = _get_resolved_spec(env, axis.step)
573
+ if entry.name in view_constant_to_access_packing:
574
+ axes_specs.append(view_constant_to_access_packing[entry.name])
575
+ else:
576
+ raise CompileError(axis.step.pos, INVALID_ERR)
577
+
578
+ else:
579
+ raise CompileError(axis.step.pos, INVALID_ERR)
580
+
581
+ # First, find out if we have a ::1 somewhere
582
+ contig_dim = 0
583
+ is_contig = False
584
+ for idx, (access, packing) in enumerate(axes_specs):
585
+ if packing == 'cfcontig':
586
+ if is_contig:
587
+ raise CompileError(axis.step.pos, BOTH_CF_ERR)
588
+
589
+ contig_dim = idx
590
+ axes_specs[idx] = (access, 'contig')
591
+ is_contig = True
592
+
593
+ if is_contig:
594
+ # We have a ::1 somewhere, see if we're C or Fortran contiguous
595
+ if contig_dim == len(axes) - 1:
596
+ is_c_contig = True
597
+ else:
598
+ is_f_contig = True
599
+
600
+ if contig_dim and not axes_specs[contig_dim - 1][0] in ('full', 'ptr'):
601
+ raise CompileError(axes[contig_dim].pos,
602
+ "Fortran contiguous specifier must follow an indirect dimension")
603
+
604
+ if is_c_contig:
605
+ # Contiguous in the last dimension, find the last indirect dimension
606
+ contig_dim = -1
607
+ for idx, (access, packing) in enumerate(reversed(axes_specs)):
608
+ if access in ('ptr', 'full'):
609
+ contig_dim = len(axes) - idx - 1
610
+
611
+ # Replace 'strided' with 'follow' for any dimension following the last
612
+ # indirect dimension, the first dimension or the dimension following
613
+ # the ::1.
614
+ # int[::indirect, ::1, :, :]
615
+ # ^ ^
616
+ # int[::indirect, :, :, ::1]
617
+ # ^ ^
618
+ start = contig_dim + 1
619
+ stop = len(axes) - is_c_contig
620
+ for idx, (access, packing) in enumerate(axes_specs[start:stop]):
621
+ idx = contig_dim + 1 + idx
622
+ if access != 'direct':
623
+ raise CompileError(axes[idx].pos,
624
+ "Indirect dimension may not follow "
625
+ "Fortran contiguous dimension")
626
+ if packing == 'contig':
627
+ raise CompileError(axes[idx].pos,
628
+ "Dimension may not be contiguous")
629
+ axes_specs[idx] = (access, cf_packing)
630
+
631
+ if is_c_contig:
632
+ # For C contiguity, we need to fix the 'contig' dimension
633
+ # after the loop
634
+ a, p = axes_specs[-1]
635
+ axes_specs[-1] = a, 'contig'
636
+
637
+ validate_axes_specs([axis.start.pos for axis in axes],
638
+ axes_specs,
639
+ is_c_contig,
640
+ is_f_contig)
641
+
642
+ return axes_specs
643
+
644
+
645
+ def validate_axes(pos, axes):
646
+ if len(axes) >= Options.buffer_max_dims:
647
+ error(pos, "More dimensions than the maximum number"
648
+ " of buffer dimensions were used.")
649
+ return False
650
+
651
+ return True
652
+
653
+
654
+ def is_cf_contig(specs):
655
+ is_c_contig = is_f_contig = False
656
+
657
+ if len(specs) == 1 and specs == [('direct', 'contig')]:
658
+ is_c_contig = True
659
+
660
+ elif (specs[-1] == ('direct','contig') and
661
+ all(axis == ('direct','follow') for axis in specs[:-1])):
662
+ # c_contiguous: 'follow', 'follow', ..., 'follow', 'contig'
663
+ is_c_contig = True
664
+
665
+ elif (len(specs) > 1 and
666
+ specs[0] == ('direct','contig') and
667
+ all(axis == ('direct','follow') for axis in specs[1:])):
668
+ # f_contiguous: 'contig', 'follow', 'follow', ..., 'follow'
669
+ is_f_contig = True
670
+
671
+ return is_c_contig, is_f_contig
672
+
673
+
674
+ def get_mode(specs):
675
+ is_c_contig, is_f_contig = is_cf_contig(specs)
676
+
677
+ if is_c_contig:
678
+ return 'c'
679
+ elif is_f_contig:
680
+ return 'fortran'
681
+
682
+ for access, packing in specs:
683
+ if access in ('ptr', 'full'):
684
+ return 'full'
685
+
686
+ return 'strided'
687
+
688
+ view_constant_to_access_packing = {
689
+ 'generic': ('full', 'strided'),
690
+ 'strided': ('direct', 'strided'),
691
+ 'indirect': ('ptr', 'strided'),
692
+ 'generic_contiguous': ('full', 'contig'),
693
+ 'contiguous': ('direct', 'contig'),
694
+ 'indirect_contiguous': ('ptr', 'contig'),
695
+ }
696
+
697
+ def validate_axes_specs(positions, specs, is_c_contig, is_f_contig):
698
+
699
+ packing_specs = ('contig', 'strided', 'follow')
700
+ access_specs = ('direct', 'ptr', 'full')
701
+
702
+ # is_c_contig, is_f_contig = is_cf_contig(specs)
703
+
704
+ has_contig = has_follow = has_strided = has_generic_contig = False
705
+
706
+ last_indirect_dimension = -1
707
+ for idx, (access, packing) in enumerate(specs):
708
+ if access == 'ptr':
709
+ last_indirect_dimension = idx
710
+
711
+ for idx, (pos, (access, packing)) in enumerate(zip(positions, specs)):
712
+
713
+ if not (access in access_specs and
714
+ packing in packing_specs):
715
+ raise CompileError(pos, "Invalid axes specification.")
716
+
717
+ if packing == 'strided':
718
+ has_strided = True
719
+ elif packing == 'contig':
720
+ if has_contig:
721
+ raise CompileError(pos, "Only one direct contiguous "
722
+ "axis may be specified.")
723
+
724
+ valid_contig_dims = last_indirect_dimension + 1, len(specs) - 1
725
+ if idx not in valid_contig_dims and access != 'ptr':
726
+ if last_indirect_dimension + 1 != len(specs) - 1:
727
+ dims = "dimensions %d and %d" % valid_contig_dims
728
+ else:
729
+ dims = "dimension %d" % valid_contig_dims[0]
730
+
731
+ raise CompileError(pos, "Only %s may be contiguous and direct" % dims)
732
+
733
+ has_contig = access != 'ptr'
734
+ elif packing == 'follow':
735
+ if has_strided:
736
+ raise CompileError(pos, "A memoryview cannot have both follow and strided axis specifiers.")
737
+ if not (is_c_contig or is_f_contig):
738
+ raise CompileError(pos, "Invalid use of the follow specifier.")
739
+
740
+ if access in ('ptr', 'full'):
741
+ has_strided = False
742
+
743
+ def _get_resolved_spec(env, spec):
744
+ # spec must be a NameNode or an AttributeNode
745
+ if isinstance(spec, NameNode):
746
+ return _resolve_NameNode(env, spec)
747
+ elif isinstance(spec, AttributeNode):
748
+ return _resolve_AttributeNode(env, spec)
749
+ else:
750
+ raise CompileError(spec.pos, INVALID_ERR)
751
+
752
+ def _resolve_NameNode(env, node):
753
+ try:
754
+ resolved_name = env.lookup(node.name).name
755
+ except AttributeError:
756
+ raise CompileError(node.pos, INVALID_ERR)
757
+
758
+ viewscope = env.global_scope().context.cython_scope.viewscope
759
+ entry = viewscope.lookup(resolved_name)
760
+ if entry is None:
761
+ raise CompileError(node.pos, NOT_CIMPORTED_ERR)
762
+
763
+ return entry
764
+
765
+ def _resolve_AttributeNode(env, node):
766
+ path = []
767
+ while isinstance(node, AttributeNode):
768
+ path.insert(0, node.attribute)
769
+ node = node.obj
770
+ if isinstance(node, NameNode):
771
+ path.insert(0, node.name)
772
+ else:
773
+ raise CompileError(node.pos, EXPR_ERR)
774
+ modnames = path[:-1]
775
+ # must be at least 1 module name, o/w not an AttributeNode.
776
+ assert modnames
777
+
778
+ scope = env
779
+ for modname in modnames:
780
+ mod = scope.lookup(modname)
781
+ if not mod or not mod.as_module:
782
+ raise CompileError(
783
+ node.pos, "undeclared name not builtin: %s" % modname)
784
+ scope = mod.as_module
785
+
786
+ entry = scope.lookup(path[-1])
787
+ if not entry:
788
+ raise CompileError(node.pos, "No such attribute '%s'" % path[-1])
789
+
790
+ return entry
791
+
792
+ #
793
+ ### Utility loading
794
+ #
795
+
796
+ def load_memview_cy_utility(util_code_name, context=None, **kwargs):
797
+ return CythonUtilityCode.load(util_code_name, "MemoryView.pyx",
798
+ context=context, **kwargs)
799
+
800
+ def load_memview_c_utility(util_code_name, context=None, **kwargs):
801
+ if context is None:
802
+ return UtilityCode.load(util_code_name, "MemoryView_C.c", **kwargs)
803
+ else:
804
+ return TempitaUtilityCode.load(util_code_name, "MemoryView_C.c",
805
+ context=context, **kwargs)
806
+
807
+ def use_cython_array_utility_code(env):
808
+ cython_scope = env.global_scope().context.cython_scope
809
+ cython_scope.load_cythonscope()
810
+ cython_scope.viewscope.lookup('array_cwrapper').used = True
811
+
812
+ context = {
813
+ 'memview_struct_name': memview_objstruct_cname,
814
+ 'max_dims': Options.buffer_max_dims,
815
+ 'memviewslice_name': memviewslice_cname,
816
+ 'memslice_init': PyrexTypes.MemoryViewSliceType.default_value,
817
+ 'THREAD_LOCKS_PREALLOCATED': 8,
818
+ }
819
+ memviewslice_declare_code = load_memview_c_utility(
820
+ "MemviewSliceStruct",
821
+ context=context,
822
+ requires=[])
823
+
824
+ atomic_utility = load_memview_c_utility("Atomics", context)
825
+
826
+ memviewslice_init_code = load_memview_c_utility(
827
+ "MemviewSliceInit",
828
+ context=dict(context, BUF_MAX_NDIMS=Options.buffer_max_dims),
829
+ requires=[memviewslice_declare_code,
830
+ atomic_utility],
831
+ )
832
+
833
+ memviewslice_index_helpers = load_memview_c_utility("MemviewSliceIndex")
834
+
835
+ typeinfo_to_format_code = load_memview_cy_utility(
836
+ "BufferFormatFromTypeInfo", requires=[Buffer._typeinfo_to_format_code])
837
+
838
+ is_contig_utility = load_memview_c_utility("MemviewSliceIsContig", context)
839
+ overlapping_utility = load_memview_c_utility("OverlappingSlices", context)
840
+ copy_contents_new_utility = load_memview_c_utility(
841
+ "MemviewSliceCopyTemplate",
842
+ context,
843
+ requires=[], # require cython_array_utility_code
844
+ )
845
+
846
+ view_utility_code = load_memview_cy_utility(
847
+ "View.MemoryView",
848
+ context=context,
849
+ requires=[Buffer.GetAndReleaseBufferUtilityCode(),
850
+ Buffer.buffer_struct_declare_code,
851
+ Buffer.buffer_formats_declare_code,
852
+ memviewslice_init_code,
853
+ is_contig_utility,
854
+ overlapping_utility,
855
+ copy_contents_new_utility,
856
+ ],
857
+ )
858
+ view_utility_allowlist = ('array', 'memoryview', 'array_cwrapper',
859
+ 'generic', 'strided', 'indirect', 'contiguous',
860
+ 'indirect_contiguous')
861
+
862
+ memviewslice_declare_code.requires.append(view_utility_code)
863
+ copy_contents_new_utility.requires.append(view_utility_code)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/ModuleNode.py ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Nodes.py ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Options.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Cython - Compilation-wide options and pragma declarations
3
+ #
4
+
5
+ from __future__ import absolute_import
6
+
7
+ import os
8
+
9
+ from .. import Utils
10
+
11
+
12
+ class ShouldBeFromDirective(object):
13
+
14
+ known_directives = []
15
+
16
+ def __init__(self, options_name, directive_name=None, disallow=False):
17
+ self.options_name = options_name
18
+ self.directive_name = directive_name or options_name
19
+ self.disallow = disallow
20
+ self.known_directives.append(self)
21
+
22
+ def __nonzero__(self):
23
+ self._bad_access()
24
+
25
+ def __int__(self):
26
+ self._bad_access()
27
+
28
+ def _bad_access(self):
29
+ raise RuntimeError(repr(self))
30
+
31
+ def __repr__(self):
32
+ return "Illegal access of '%s' from Options module rather than directive '%s'" % (
33
+ self.options_name, self.directive_name)
34
+
35
+
36
+ """
37
+ The members of this module are documented using autodata in
38
+ Cython/docs/src/reference/compilation.rst.
39
+ See https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-autoattribute
40
+ for how autodata works.
41
+ Descriptions of those members should start with a #:
42
+ Donc forget to keep the docs in sync by removing and adding
43
+ the members in both this file and the .rst file.
44
+ """
45
+
46
+ #: Whether or not to include docstring in the Python extension. If False, the binary size
47
+ #: will be smaller, but the ``__doc__`` attribute of any class or function will be an
48
+ #: empty string.
49
+ docstrings = True
50
+
51
+ #: Embed the source code position in the docstrings of functions and classes.
52
+ embed_pos_in_docstring = False
53
+
54
+ # undocumented
55
+ pre_import = None
56
+
57
+ #: Decref global variables in each module on exit for garbage collection.
58
+ #: 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects
59
+ #: Mostly for reducing noise in Valgrind as it typically executes at process exit
60
+ #: (when all memory will be reclaimed anyways).
61
+ #: Note that directly or indirectly executed cleanup code that makes use of global
62
+ #: variables or types may no longer be safe when enabling the respective level since
63
+ #: there is no guaranteed order in which the (reference counted) objects will
64
+ #: be cleaned up. The order can change due to live references and reference cycles.
65
+ generate_cleanup_code = False
66
+
67
+ #: Should tp_clear() set object fields to None instead of clearing them to NULL?
68
+ clear_to_none = True
69
+
70
+ #: Generate an annotated HTML version of the input source files for debugging and optimisation purposes.
71
+ #: This has the same effect as the ``annotate`` argument in :func:`cythonize`.
72
+ annotate = False
73
+
74
+ # When annotating source files in HTML, include coverage information from
75
+ # this file.
76
+ annotate_coverage_xml = None
77
+
78
+ #: This will abort the compilation on the first error occurred rather than trying
79
+ #: to keep going and printing further error messages.
80
+ fast_fail = False
81
+
82
+ #: Turn all warnings into errors.
83
+ warning_errors = False
84
+
85
+ #: Make unknown names an error. Python raises a NameError when
86
+ #: encountering unknown names at runtime, whereas this option makes
87
+ #: them a compile time error. If you want full Python compatibility,
88
+ #: you should disable this option and also 'cache_builtins'.
89
+ error_on_unknown_names = True
90
+
91
+ #: Make uninitialized local variable reference a compile time error.
92
+ #: Python raises UnboundLocalError at runtime, whereas this option makes
93
+ #: them a compile time error. Note that this option affects only variables
94
+ #: of "python object" type.
95
+ error_on_uninitialized = True
96
+
97
+ #: This will convert statements of the form ``for i in range(...)``
98
+ #: to ``for i from ...`` when ``i`` is a C integer type, and the direction
99
+ #: (i.e. sign of step) can be determined.
100
+ #: WARNING: This may change the semantics if the range causes assignment to
101
+ #: i to overflow. Specifically, if this option is set, an error will be
102
+ #: raised before the loop is entered, whereas without this option the loop
103
+ #: will execute until an overflowing value is encountered.
104
+ convert_range = True
105
+
106
+ #: Perform lookups on builtin names only once, at module initialisation
107
+ #: time. This will prevent the module from getting imported if a
108
+ #: builtin name that it uses cannot be found during initialisation.
109
+ #: Default is True.
110
+ #: Note that some legacy builtins are automatically remapped
111
+ #: from their Python 2 names to their Python 3 names by Cython
112
+ #: when building in Python 3.x,
113
+ #: so that they do not get in the way even if this option is enabled.
114
+ cache_builtins = True
115
+
116
+ #: Generate branch prediction hints to speed up error handling etc.
117
+ gcc_branch_hints = True
118
+
119
+ #: Enable this to allow one to write ``your_module.foo = ...`` to overwrite the
120
+ #: definition if the cpdef function foo, at the cost of an extra dictionary
121
+ #: lookup on every call.
122
+ #: If this is false it generates only the Python wrapper and no override check.
123
+ lookup_module_cpdef = False
124
+
125
+ #: Whether or not to embed the Python interpreter, for use in making a
126
+ #: standalone executable or calling from external libraries.
127
+ #: This will provide a C function which initialises the interpreter and
128
+ #: executes the body of this module.
129
+ #: See `this demo <https://github.com/cython/cython/tree/master/Demos/embed>`_
130
+ #: for a concrete example.
131
+ #: If true, the initialisation function is the C main() function, but
132
+ #: this option can also be set to a non-empty string to provide a function name explicitly.
133
+ #: Default is False.
134
+ embed = None
135
+
136
+ # In previous iterations of Cython, globals() gave the first non-Cython module
137
+ # globals in the call stack. Sage relies on this behavior for variable injection.
138
+ old_style_globals = ShouldBeFromDirective('old_style_globals')
139
+
140
+ #: Allows cimporting from a pyx file without a pxd file.
141
+ cimport_from_pyx = False
142
+
143
+ #: Maximum number of dimensions for buffers -- set lower than number of
144
+ #: dimensions in numpy, as
145
+ #: slices are passed by value and involve a lot of copying.
146
+ buffer_max_dims = 8
147
+
148
+ #: Number of function closure instances to keep in a freelist (0: no freelists)
149
+ closure_freelist_size = 8
150
+
151
+
152
+ def get_directive_defaults():
153
+ # To add an item to this list, all accesses should be changed to use the new
154
+ # directive, and the global option itself should be set to an instance of
155
+ # ShouldBeFromDirective.
156
+ for old_option in ShouldBeFromDirective.known_directives:
157
+ value = globals().get(old_option.options_name)
158
+ assert old_option.directive_name in _directive_defaults
159
+ if not isinstance(value, ShouldBeFromDirective):
160
+ if old_option.disallow:
161
+ raise RuntimeError(
162
+ "Option '%s' must be set from directive '%s'" % (
163
+ old_option.option_name, old_option.directive_name))
164
+ else:
165
+ # Warn?
166
+ _directive_defaults[old_option.directive_name] = value
167
+ return _directive_defaults
168
+
169
+ def copy_inherited_directives(outer_directives, **new_directives):
170
+ # A few directives are not copied downwards and this function removes them.
171
+ # For example, test_assert_path_exists and test_fail_if_path_exists should not be inherited
172
+ # otherwise they can produce very misleading test failures
173
+ new_directives_out = dict(outer_directives)
174
+ for name in ('test_assert_path_exists', 'test_fail_if_path_exists', 'test_assert_c_code_has', 'test_fail_if_c_code_has'):
175
+ new_directives_out.pop(name, None)
176
+ new_directives_out.update(new_directives)
177
+ return new_directives_out
178
+
179
+ # Declare compiler directives
180
+ _directive_defaults = {
181
+ 'binding': True, # was False before 3.0
182
+ 'boundscheck' : True,
183
+ 'nonecheck' : False,
184
+ 'initializedcheck' : True,
185
+ 'embedsignature': False,
186
+ 'embedsignature.format': 'c',
187
+ 'auto_cpdef': False,
188
+ 'auto_pickle': None,
189
+ 'cdivision': False, # was True before 0.12
190
+ 'cdivision_warnings': False,
191
+ 'cpow': None, # was True before 3.0
192
+ # None (not set by user) is treated as slightly different from False
193
+ 'c_api_binop_methods': False, # was True before 3.0
194
+ 'overflowcheck': False,
195
+ 'overflowcheck.fold': True,
196
+ 'always_allow_keywords': True,
197
+ 'allow_none_for_extension_args': True,
198
+ 'wraparound' : True,
199
+ 'ccomplex' : False, # use C99/C++ for complex types and arith
200
+ 'callspec' : "",
201
+ 'nogil' : False,
202
+ 'gil' : False,
203
+ 'with_gil' : False,
204
+ 'profile': False,
205
+ 'linetrace': False,
206
+ 'emit_code_comments': True, # copy original source code into C code comments
207
+ 'annotation_typing': True, # read type declarations from Python function annotations
208
+ 'infer_types': None,
209
+ 'infer_types.verbose': False,
210
+ 'autotestdict': True,
211
+ 'autotestdict.cdef': False,
212
+ 'autotestdict.all': False,
213
+ 'language_level': None,
214
+ 'fast_getattr': False, # Undocumented until we come up with a better way to handle this everywhere.
215
+ 'py2_import': False, # For backward compatibility of Cython's source code in Py3 source mode
216
+ 'preliminary_late_includes_cy28': False, # Temporary directive in 0.28, to be removed in a later version (see GH#2079).
217
+ 'iterable_coroutine': False, # Make async coroutines backwards compatible with the old asyncio yield-from syntax.
218
+ 'c_string_type': 'bytes',
219
+ 'c_string_encoding': '',
220
+ 'type_version_tag': True, # enables Py_TPFLAGS_HAVE_VERSION_TAG on extension types
221
+ 'unraisable_tracebacks': True,
222
+ 'old_style_globals': False,
223
+ 'np_pythran': False,
224
+ 'fast_gil': False,
225
+ 'cpp_locals': False, # uses std::optional for C++ locals, so that they work more like Python locals
226
+ 'legacy_implicit_noexcept': False,
227
+
228
+ # set __file__ and/or __path__ to known source/target path at import time (instead of not having them available)
229
+ 'set_initial_path' : None, # SOURCEFILE or "/full/path/to/module"
230
+
231
+ 'warn': None,
232
+ 'warn.undeclared': False,
233
+ 'warn.unreachable': True,
234
+ 'warn.maybe_uninitialized': False,
235
+ 'warn.unused': False,
236
+ 'warn.unused_arg': False,
237
+ 'warn.unused_result': False,
238
+ 'warn.multiple_declarators': True,
239
+ 'show_performance_hints': True,
240
+
241
+ # optimizations
242
+ 'optimize.inline_defnode_calls': True,
243
+ 'optimize.unpack_method_calls': True, # increases code size when True
244
+ 'optimize.unpack_method_calls_in_pyinit': False, # uselessly increases code size when True
245
+ 'optimize.use_switch': True,
246
+
247
+ # remove unreachable code
248
+ 'remove_unreachable': True,
249
+
250
+ # control flow debug directives
251
+ 'control_flow.dot_output': "", # Graphviz output filename
252
+ 'control_flow.dot_annotate_defs': False, # Annotate definitions
253
+
254
+ # test support
255
+ 'test_assert_path_exists' : [],
256
+ 'test_fail_if_path_exists' : [],
257
+ 'test_assert_c_code_has' : [],
258
+ 'test_fail_if_c_code_has' : [],
259
+
260
+ # experimental, subject to change
261
+ 'formal_grammar': False,
262
+ }
263
+
264
+ # Extra warning directives
265
+ extra_warnings = {
266
+ 'warn.maybe_uninitialized': True,
267
+ 'warn.unreachable': True,
268
+ 'warn.unused': True,
269
+ }
270
+
271
+ def one_of(*args):
272
+ def validate(name, value):
273
+ if value not in args:
274
+ raise ValueError("%s directive must be one of %s, got '%s'" % (
275
+ name, args, value))
276
+ else:
277
+ return value
278
+ return validate
279
+
280
+
281
+ def normalise_encoding_name(option_name, encoding):
282
+ """
283
+ >>> normalise_encoding_name('c_string_encoding', 'ascii')
284
+ 'ascii'
285
+ >>> normalise_encoding_name('c_string_encoding', 'AsCIi')
286
+ 'ascii'
287
+ >>> normalise_encoding_name('c_string_encoding', 'us-ascii')
288
+ 'ascii'
289
+ >>> normalise_encoding_name('c_string_encoding', 'utF8')
290
+ 'utf8'
291
+ >>> normalise_encoding_name('c_string_encoding', 'utF-8')
292
+ 'utf8'
293
+ >>> normalise_encoding_name('c_string_encoding', 'deFAuLT')
294
+ 'default'
295
+ >>> normalise_encoding_name('c_string_encoding', 'default')
296
+ 'default'
297
+ >>> normalise_encoding_name('c_string_encoding', 'SeriousLyNoSuch--Encoding')
298
+ 'SeriousLyNoSuch--Encoding'
299
+ """
300
+ if not encoding:
301
+ return ''
302
+ if encoding.lower() in ('default', 'ascii', 'utf8'):
303
+ return encoding.lower()
304
+ import codecs
305
+ try:
306
+ decoder = codecs.getdecoder(encoding)
307
+ except LookupError:
308
+ return encoding # may exists at runtime ...
309
+ for name in ('ascii', 'utf8'):
310
+ if codecs.getdecoder(name) == decoder:
311
+ return name
312
+ return encoding
313
+
314
+ # use as a sential value to defer analysis of the arguments
315
+ # instead of analysing them in InterpretCompilerDirectives. The dataclass directives are quite
316
+ # complicated and it's easier to deal with them at the point the dataclass is created
317
+ class DEFER_ANALYSIS_OF_ARGUMENTS:
318
+ pass
319
+ DEFER_ANALYSIS_OF_ARGUMENTS = DEFER_ANALYSIS_OF_ARGUMENTS()
320
+
321
+ # Override types possibilities above, if needed
322
+ directive_types = {
323
+ 'language_level': str, # values can be None/2/3/'3str', where None == 2+warning
324
+ 'auto_pickle': bool,
325
+ 'locals': dict,
326
+ 'final' : bool, # final cdef classes and methods
327
+ 'collection_type': one_of('sequence'),
328
+ 'nogil' : DEFER_ANALYSIS_OF_ARGUMENTS,
329
+ 'gil' : DEFER_ANALYSIS_OF_ARGUMENTS,
330
+ 'with_gil' : None,
331
+ 'internal' : bool, # cdef class visibility in the module dict
332
+ 'infer_types' : bool, # values can be True/None/False
333
+ 'binding' : bool,
334
+ 'cfunc' : None, # decorators do not take directive value
335
+ 'ccall' : None,
336
+ 'ufunc': None,
337
+ 'cpow' : bool,
338
+ 'inline' : None,
339
+ 'staticmethod' : None,
340
+ 'cclass' : None,
341
+ 'no_gc_clear' : bool,
342
+ 'no_gc' : bool,
343
+ 'returns' : type,
344
+ 'exceptval': type, # actually (type, check=True/False), but has its own parser
345
+ 'set_initial_path': str,
346
+ 'freelist': int,
347
+ 'c_string_type': one_of('bytes', 'bytearray', 'str', 'unicode'),
348
+ 'c_string_encoding': normalise_encoding_name,
349
+ 'trashcan': bool,
350
+ 'total_ordering': None,
351
+ 'dataclasses.dataclass': DEFER_ANALYSIS_OF_ARGUMENTS,
352
+ 'dataclasses.field': DEFER_ANALYSIS_OF_ARGUMENTS,
353
+ 'embedsignature.format': one_of('c', 'clinic', 'python'),
354
+ }
355
+
356
+ for key, val in _directive_defaults.items():
357
+ if key not in directive_types:
358
+ directive_types[key] = type(val)
359
+
360
+ directive_scopes = { # defaults to available everywhere
361
+ # 'module', 'function', 'class', 'with statement'
362
+ 'auto_pickle': ('module', 'cclass'),
363
+ 'final' : ('cclass', 'function'),
364
+ 'collection_type': ('cclass',),
365
+ 'nogil' : ('function', 'with statement'),
366
+ 'gil' : ('with statement'),
367
+ 'with_gil' : ('function',),
368
+ 'inline' : ('function',),
369
+ 'cfunc' : ('function', 'with statement'),
370
+ 'ccall' : ('function', 'with statement'),
371
+ 'returns' : ('function',),
372
+ 'exceptval' : ('function',),
373
+ 'locals' : ('function',),
374
+ 'staticmethod' : ('function',), # FIXME: analysis currently lacks more specific function scope
375
+ 'no_gc_clear' : ('cclass',),
376
+ 'no_gc' : ('cclass',),
377
+ 'internal' : ('cclass',),
378
+ 'cclass' : ('class', 'cclass', 'with statement'),
379
+ 'autotestdict' : ('module',),
380
+ 'autotestdict.all' : ('module',),
381
+ 'autotestdict.cdef' : ('module',),
382
+ 'set_initial_path' : ('module',),
383
+ 'test_assert_path_exists' : ('function', 'class', 'cclass'),
384
+ 'test_fail_if_path_exists' : ('function', 'class', 'cclass'),
385
+ 'test_assert_c_code_has' : ('module',),
386
+ 'test_fail_if_c_code_has' : ('module',),
387
+ 'freelist': ('cclass',),
388
+ 'emit_code_comments': ('module',),
389
+ # Avoid scope-specific to/from_py_functions for c_string.
390
+ 'c_string_type': ('module',),
391
+ 'c_string_encoding': ('module',),
392
+ 'type_version_tag': ('module', 'cclass'),
393
+ 'language_level': ('module',),
394
+ # globals() could conceivably be controlled at a finer granularity,
395
+ # but that would complicate the implementation
396
+ 'old_style_globals': ('module',),
397
+ 'np_pythran': ('module',),
398
+ 'fast_gil': ('module',),
399
+ 'iterable_coroutine': ('module', 'function'),
400
+ 'trashcan' : ('cclass',),
401
+ 'total_ordering': ('class', 'cclass'),
402
+ 'dataclasses.dataclass' : ('class', 'cclass'),
403
+ 'cpp_locals': ('module', 'function', 'cclass'), # I don't think they make sense in a with_statement
404
+ 'ufunc': ('function',),
405
+ 'legacy_implicit_noexcept': ('module', ),
406
+ }
407
+
408
+
409
+ # A list of directives that (when used as a decorator) are only applied to
410
+ # the object they decorate and not to its children.
411
+ immediate_decorator_directives = {
412
+ 'cfunc', 'ccall', 'cclass', 'dataclasses.dataclass', 'ufunc',
413
+ # function signature directives
414
+ 'inline', 'exceptval', 'returns', 'with_gil', # 'nogil',
415
+ # class directives
416
+ 'freelist', 'no_gc', 'no_gc_clear', 'type_version_tag', 'final',
417
+ 'auto_pickle', 'internal', 'collection_type', 'total_ordering',
418
+ # testing directives
419
+ 'test_fail_if_path_exists', 'test_assert_path_exists',
420
+ }
421
+
422
+
423
+ def parse_directive_value(name, value, relaxed_bool=False):
424
+ """
425
+ Parses value as an option value for the given name and returns
426
+ the interpreted value. None is returned if the option does not exist.
427
+
428
+ >>> print(parse_directive_value('nonexisting', 'asdf asdfd'))
429
+ None
430
+ >>> parse_directive_value('boundscheck', 'True')
431
+ True
432
+ >>> parse_directive_value('boundscheck', 'true')
433
+ Traceback (most recent call last):
434
+ ...
435
+ ValueError: boundscheck directive must be set to True or False, got 'true'
436
+
437
+ >>> parse_directive_value('c_string_encoding', 'us-ascii')
438
+ 'ascii'
439
+ >>> parse_directive_value('c_string_type', 'str')
440
+ 'str'
441
+ >>> parse_directive_value('c_string_type', 'bytes')
442
+ 'bytes'
443
+ >>> parse_directive_value('c_string_type', 'bytearray')
444
+ 'bytearray'
445
+ >>> parse_directive_value('c_string_type', 'unicode')
446
+ 'unicode'
447
+ >>> parse_directive_value('c_string_type', 'unnicode')
448
+ Traceback (most recent call last):
449
+ ValueError: c_string_type directive must be one of ('bytes', 'bytearray', 'str', 'unicode'), got 'unnicode'
450
+ """
451
+ type = directive_types.get(name)
452
+ if not type:
453
+ return None
454
+ orig_value = value
455
+ if type is bool:
456
+ value = str(value)
457
+ if value == 'True':
458
+ return True
459
+ if value == 'False':
460
+ return False
461
+ if relaxed_bool:
462
+ value = value.lower()
463
+ if value in ("true", "yes"):
464
+ return True
465
+ elif value in ("false", "no"):
466
+ return False
467
+ raise ValueError("%s directive must be set to True or False, got '%s'" % (
468
+ name, orig_value))
469
+ elif type is int:
470
+ try:
471
+ return int(value)
472
+ except ValueError:
473
+ raise ValueError("%s directive must be set to an integer, got '%s'" % (
474
+ name, orig_value))
475
+ elif type is str:
476
+ return str(value)
477
+ elif callable(type):
478
+ return type(name, value)
479
+ else:
480
+ assert False
481
+
482
+
483
+ def parse_directive_list(s, relaxed_bool=False, ignore_unknown=False,
484
+ current_settings=None):
485
+ """
486
+ Parses a comma-separated list of pragma options. Whitespace
487
+ is not considered.
488
+
489
+ >>> parse_directive_list(' ')
490
+ {}
491
+ >>> (parse_directive_list('boundscheck=True') ==
492
+ ... {'boundscheck': True})
493
+ True
494
+ >>> parse_directive_list(' asdf')
495
+ Traceback (most recent call last):
496
+ ...
497
+ ValueError: Expected "=" in option "asdf"
498
+ >>> parse_directive_list('boundscheck=hey')
499
+ Traceback (most recent call last):
500
+ ...
501
+ ValueError: boundscheck directive must be set to True or False, got 'hey'
502
+ >>> parse_directive_list('unknown=True')
503
+ Traceback (most recent call last):
504
+ ...
505
+ ValueError: Unknown option: "unknown"
506
+ >>> warnings = parse_directive_list('warn.all=True')
507
+ >>> len(warnings) > 1
508
+ True
509
+ >>> sum(warnings.values()) == len(warnings) # all true.
510
+ True
511
+ """
512
+ if current_settings is None:
513
+ result = {}
514
+ else:
515
+ result = current_settings
516
+ for item in s.split(','):
517
+ item = item.strip()
518
+ if not item:
519
+ continue
520
+ if '=' not in item:
521
+ raise ValueError('Expected "=" in option "%s"' % item)
522
+ name, value = [s.strip() for s in item.strip().split('=', 1)]
523
+ if name not in _directive_defaults:
524
+ found = False
525
+ if name.endswith('.all'):
526
+ prefix = name[:-3]
527
+ for directive in _directive_defaults:
528
+ if directive.startswith(prefix):
529
+ found = True
530
+ parsed_value = parse_directive_value(directive, value, relaxed_bool=relaxed_bool)
531
+ result[directive] = parsed_value
532
+ if not found and not ignore_unknown:
533
+ raise ValueError('Unknown option: "%s"' % name)
534
+ elif directive_types.get(name) is list:
535
+ if name in result:
536
+ result[name].append(value)
537
+ else:
538
+ result[name] = [value]
539
+ else:
540
+ parsed_value = parse_directive_value(name, value, relaxed_bool=relaxed_bool)
541
+ result[name] = parsed_value
542
+ return result
543
+
544
+
545
+ def parse_variable_value(value):
546
+ """
547
+ Parses value as an option value for the given name and returns
548
+ the interpreted value.
549
+
550
+ >>> parse_variable_value('True')
551
+ True
552
+ >>> parse_variable_value('true')
553
+ 'true'
554
+ >>> parse_variable_value('us-ascii')
555
+ 'us-ascii'
556
+ >>> parse_variable_value('str')
557
+ 'str'
558
+ >>> parse_variable_value('123')
559
+ 123
560
+ >>> parse_variable_value('1.23')
561
+ 1.23
562
+
563
+ """
564
+ if value == "True":
565
+ return True
566
+ elif value == "False":
567
+ return False
568
+ elif value == "None":
569
+ return None
570
+ elif value.isdigit():
571
+ return int(value)
572
+ else:
573
+ try:
574
+ value = float(value)
575
+ except Exception:
576
+ # Not a float
577
+ pass
578
+ return value
579
+
580
+
581
+ def parse_compile_time_env(s, current_settings=None):
582
+ """
583
+ Parses a comma-separated list of pragma options. Whitespace
584
+ is not considered.
585
+
586
+ >>> parse_compile_time_env(' ')
587
+ {}
588
+ >>> (parse_compile_time_env('HAVE_OPENMP=True') ==
589
+ ... {'HAVE_OPENMP': True})
590
+ True
591
+ >>> parse_compile_time_env(' asdf')
592
+ Traceback (most recent call last):
593
+ ...
594
+ ValueError: Expected "=" in option "asdf"
595
+ >>> parse_compile_time_env('NUM_THREADS=4') == {'NUM_THREADS': 4}
596
+ True
597
+ >>> parse_compile_time_env('unknown=anything') == {'unknown': 'anything'}
598
+ True
599
+ """
600
+ if current_settings is None:
601
+ result = {}
602
+ else:
603
+ result = current_settings
604
+ for item in s.split(','):
605
+ item = item.strip()
606
+ if not item:
607
+ continue
608
+ if '=' not in item:
609
+ raise ValueError('Expected "=" in option "%s"' % item)
610
+ name, value = [s.strip() for s in item.split('=', 1)]
611
+ result[name] = parse_variable_value(value)
612
+ return result
613
+
614
+
615
+ # ------------------------------------------------------------------------
616
+ # CompilationOptions are constructed from user input and are the `option`
617
+ # object passed throughout the compilation pipeline.
618
+
619
+ class CompilationOptions(object):
620
+ r"""
621
+ See default_options at the end of this module for a list of all possible
622
+ options and CmdLine.usage and CmdLine.parse_command_line() for their
623
+ meaning.
624
+ """
625
+ def __init__(self, defaults=None, **kw):
626
+ self.include_path = []
627
+ if defaults:
628
+ if isinstance(defaults, CompilationOptions):
629
+ defaults = defaults.__dict__
630
+ else:
631
+ defaults = default_options
632
+
633
+ options = dict(defaults)
634
+ options.update(kw)
635
+
636
+ # let's assume 'default_options' contains a value for most known compiler options
637
+ # and validate against them
638
+ unknown_options = set(options) - set(default_options)
639
+ # ignore valid options that are not in the defaults
640
+ unknown_options.difference_update(['include_path'])
641
+ if unknown_options:
642
+ message = "got unknown compilation option%s, please remove: %s" % (
643
+ 's' if len(unknown_options) > 1 else '',
644
+ ', '.join(unknown_options))
645
+ raise ValueError(message)
646
+
647
+ directive_defaults = get_directive_defaults()
648
+ directives = dict(options['compiler_directives']) # copy mutable field
649
+ # check for invalid directives
650
+ unknown_directives = set(directives) - set(directive_defaults)
651
+ if unknown_directives:
652
+ message = "got unknown compiler directive%s: %s" % (
653
+ 's' if len(unknown_directives) > 1 else '',
654
+ ', '.join(unknown_directives))
655
+ raise ValueError(message)
656
+ options['compiler_directives'] = directives
657
+ if directives.get('np_pythran', False) and not options['cplus']:
658
+ import warnings
659
+ warnings.warn("C++ mode forced when in Pythran mode!")
660
+ options['cplus'] = True
661
+ if 'language_level' not in kw and directives.get('language_level'):
662
+ options['language_level'] = directives['language_level']
663
+ elif not options.get('language_level'):
664
+ options['language_level'] = directive_defaults.get('language_level')
665
+ if 'formal_grammar' in directives and 'formal_grammar' not in kw:
666
+ options['formal_grammar'] = directives['formal_grammar']
667
+ if options['cache'] is True:
668
+ options['cache'] = os.path.join(Utils.get_cython_cache_dir(), 'compiler')
669
+
670
+ self.__dict__.update(options)
671
+
672
+ def configure_language_defaults(self, source_extension):
673
+ if source_extension == 'py':
674
+ if self.compiler_directives.get('binding') is None:
675
+ self.compiler_directives['binding'] = True
676
+
677
+ def get_fingerprint(self):
678
+ r"""
679
+ Return a string that contains all the options that are relevant for cache invalidation.
680
+ """
681
+ # Collect only the data that can affect the generated file(s).
682
+ data = {}
683
+
684
+ for key, value in self.__dict__.items():
685
+ if key in ['show_version', 'errors_to_stderr', 'verbose', 'quiet']:
686
+ # verbosity flags have no influence on the compilation result
687
+ continue
688
+ elif key in ['output_file', 'output_dir']:
689
+ # ignore the exact name of the output file
690
+ continue
691
+ elif key in ['depfile']:
692
+ # external build system dependency tracking file does not influence outputs
693
+ continue
694
+ elif key in ['timestamps']:
695
+ # the cache cares about the content of files, not about the timestamps of sources
696
+ continue
697
+ elif key in ['cache']:
698
+ # hopefully caching has no influence on the compilation result
699
+ continue
700
+ elif key in ['compiler_directives']:
701
+ # directives passed on to the C compiler do not influence the generated C code
702
+ continue
703
+ elif key in ['include_path']:
704
+ # this path changes which headers are tracked as dependencies,
705
+ # it has no influence on the generated C code
706
+ continue
707
+ elif key in ['working_path']:
708
+ # this path changes where modules and pxd files are found;
709
+ # their content is part of the fingerprint anyway, their
710
+ # absolute path does not matter
711
+ continue
712
+ elif key in ['create_extension']:
713
+ # create_extension() has already mangled the options, e.g.,
714
+ # embedded_metadata, when the fingerprint is computed so we
715
+ # ignore it here.
716
+ continue
717
+ elif key in ['build_dir']:
718
+ # the (temporary) directory where we collect dependencies
719
+ # has no influence on the C output
720
+ continue
721
+ elif key in ['use_listing_file', 'generate_pxi', 'annotate', 'annotate_coverage_xml']:
722
+ # all output files are contained in the cache so the types of
723
+ # files generated must be part of the fingerprint
724
+ data[key] = value
725
+ elif key in ['formal_grammar', 'evaluate_tree_assertions']:
726
+ # these bits can change whether compilation to C passes/fails
727
+ data[key] = value
728
+ elif key in ['embedded_metadata', 'emit_linenums',
729
+ 'c_line_in_traceback', 'gdb_debug',
730
+ 'relative_path_in_code_position_comments']:
731
+ # the generated code contains additional bits when these are set
732
+ data[key] = value
733
+ elif key in ['cplus', 'language_level', 'compile_time_env', 'np_pythran']:
734
+ # assorted bits that, e.g., influence the parser
735
+ data[key] = value
736
+ elif key == ['capi_reexport_cincludes']:
737
+ if self.capi_reexport_cincludes:
738
+ # our caching implementation does not yet include fingerprints of all the header files
739
+ raise NotImplementedError('capi_reexport_cincludes is not compatible with Cython caching')
740
+ elif key == ['common_utility_include_dir']:
741
+ if self.common_utility_include_dir:
742
+ raise NotImplementedError('common_utility_include_dir is not compatible with Cython caching yet')
743
+ else:
744
+ # any unexpected option should go into the fingerprint; it's better
745
+ # to recompile than to return incorrect results from the cache.
746
+ data[key] = value
747
+
748
+ def to_fingerprint(item):
749
+ r"""
750
+ Recursively turn item into a string, turning dicts into lists with
751
+ deterministic ordering.
752
+ """
753
+ if isinstance(item, dict):
754
+ item = sorted([(repr(key), to_fingerprint(value)) for key, value in item.items()])
755
+ return repr(item)
756
+
757
+ return to_fingerprint(data)
758
+
759
+
760
+ # ------------------------------------------------------------------------
761
+ #
762
+ # Set the default options depending on the platform
763
+ #
764
+ # ------------------------------------------------------------------------
765
+
766
+ default_options = dict(
767
+ show_version=0,
768
+ use_listing_file=0,
769
+ errors_to_stderr=1,
770
+ cplus=0,
771
+ output_file=None,
772
+ depfile=None,
773
+ annotate=None,
774
+ annotate_coverage_xml=None,
775
+ generate_pxi=0,
776
+ capi_reexport_cincludes=0,
777
+ working_path="",
778
+ timestamps=None,
779
+ verbose=0,
780
+ quiet=0,
781
+ compiler_directives={},
782
+ embedded_metadata={},
783
+ evaluate_tree_assertions=False,
784
+ emit_linenums=False,
785
+ relative_path_in_code_position_comments=True,
786
+ c_line_in_traceback=True,
787
+ language_level=None, # warn but default to 2
788
+ formal_grammar=False,
789
+ gdb_debug=False,
790
+ compile_time_env=None,
791
+ module_name=None,
792
+ common_utility_include_dir=None,
793
+ output_dir=None,
794
+ build_dir=None,
795
+ cache=None,
796
+ create_extension=None,
797
+ np_pythran=False,
798
+ legacy_implicit_noexcept=None,
799
+ )
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/ParseTreeTransforms.py ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/PyrexTypes.py ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Pythran.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+ from __future__ import absolute_import
4
+
5
+ from .PyrexTypes import CType, CTypedefType, CStructOrUnionType
6
+
7
+ import cython
8
+
9
+ try:
10
+ import pythran
11
+ pythran_is_pre_0_9 = tuple(map(int, pythran.__version__.split('.')[0:2])) < (0, 9)
12
+ pythran_is_pre_0_9_6 = tuple(map(int, pythran.__version__.split('.')[0:3])) < (0, 9, 6)
13
+ except ImportError:
14
+ pythran = None
15
+ pythran_is_pre_0_9 = True
16
+ pythran_is_pre_0_9_6 = True
17
+
18
+ if pythran_is_pre_0_9_6:
19
+ pythran_builtins = '__builtin__'
20
+ else:
21
+ pythran_builtins = 'builtins'
22
+
23
+
24
+ # Pythran/Numpy specific operations
25
+
26
+ def has_np_pythran(env):
27
+ if env is None:
28
+ return False
29
+ directives = getattr(env, 'directives', None)
30
+ return (directives and directives.get('np_pythran', False))
31
+
32
+ @cython.ccall
33
+ def is_pythran_supported_dtype(type_):
34
+ if isinstance(type_, CTypedefType):
35
+ return is_pythran_supported_type(type_.typedef_base_type)
36
+ return type_.is_numeric
37
+
38
+
39
+ def pythran_type(Ty, ptype="ndarray"):
40
+ if Ty.is_buffer:
41
+ ndim,dtype = Ty.ndim, Ty.dtype
42
+ if isinstance(dtype, CStructOrUnionType):
43
+ ctype = dtype.cname
44
+ elif isinstance(dtype, CType):
45
+ ctype = dtype.sign_and_name()
46
+ elif isinstance(dtype, CTypedefType):
47
+ ctype = dtype.typedef_cname
48
+ else:
49
+ raise ValueError("unsupported type %s!" % dtype)
50
+ if pythran_is_pre_0_9:
51
+ return "pythonic::types::%s<%s,%d>" % (ptype,ctype, ndim)
52
+ else:
53
+ return "pythonic::types::%s<%s,pythonic::types::pshape<%s>>" % (ptype,ctype, ",".join(("long",)*ndim))
54
+ if Ty.is_pythran_expr:
55
+ return Ty.pythran_type
56
+ #if Ty.is_none:
57
+ # return "decltype(pythonic::builtins::None)"
58
+ if Ty.is_numeric:
59
+ return Ty.sign_and_name()
60
+ raise ValueError("unsupported pythran type %s (%s)" % (Ty, type(Ty)))
61
+
62
+
63
+ @cython.cfunc
64
+ def type_remove_ref(ty):
65
+ return "typename std::remove_reference<%s>::type" % ty
66
+
67
+
68
+ def pythran_binop_type(op, tA, tB):
69
+ if op == '**':
70
+ return 'decltype(pythonic::numpy::functor::power{}(std::declval<%s>(), std::declval<%s>()))' % (
71
+ pythran_type(tA), pythran_type(tB))
72
+ else:
73
+ return "decltype(std::declval<%s>() %s std::declval<%s>())" % (
74
+ pythran_type(tA), op, pythran_type(tB))
75
+
76
+
77
+ def pythran_unaryop_type(op, type_):
78
+ return "decltype(%sstd::declval<%s>())" % (
79
+ op, pythran_type(type_))
80
+
81
+
82
+ @cython.cfunc
83
+ def _index_access(index_code, indices):
84
+ indexing = ",".join([index_code(idx) for idx in indices])
85
+ return ('[%s]' if len(indices) == 1 else '(%s)') % indexing
86
+
87
+
88
+ def _index_type_code(index_with_type):
89
+ idx, index_type = index_with_type
90
+ if idx.is_slice:
91
+ n = 2 + int(not idx.step.is_none)
92
+ return "pythonic::%s::functor::slice{}(%s)" % (
93
+ pythran_builtins,
94
+ ",".join(["0"]*n))
95
+ elif index_type.is_int:
96
+ return "std::declval<%s>()" % index_type.sign_and_name()
97
+ elif index_type.is_pythran_expr:
98
+ return "std::declval<%s>()" % index_type.pythran_type
99
+ raise ValueError("unsupported indexing type %s!" % index_type)
100
+
101
+
102
+ def _index_code(idx):
103
+ if idx.is_slice:
104
+ values = idx.start, idx.stop, idx.step
105
+ if idx.step.is_none:
106
+ func = "contiguous_slice"
107
+ values = values[:2]
108
+ else:
109
+ func = "slice"
110
+ return "pythonic::types::%s(%s)" % (
111
+ func, ",".join((v.pythran_result() for v in values)))
112
+ elif idx.type.is_int:
113
+ return to_pythran(idx)
114
+ elif idx.type.is_pythran_expr:
115
+ return idx.pythran_result()
116
+ raise ValueError("unsupported indexing type %s" % idx.type)
117
+
118
+
119
+ def pythran_indexing_type(type_, indices):
120
+ return type_remove_ref("decltype(std::declval<%s>()%s)" % (
121
+ pythran_type(type_),
122
+ _index_access(_index_type_code, indices),
123
+ ))
124
+
125
+
126
+ def pythran_indexing_code(indices):
127
+ return _index_access(_index_code, indices)
128
+
129
+ def np_func_to_list(func):
130
+ if not func.is_numpy_attribute:
131
+ return []
132
+ return np_func_to_list(func.obj) + [func.attribute]
133
+
134
+ if pythran is None:
135
+ def pythran_is_numpy_func_supported(name):
136
+ return False
137
+ else:
138
+ def pythran_is_numpy_func_supported(func):
139
+ CurF = pythran.tables.MODULES['numpy']
140
+ FL = np_func_to_list(func)
141
+ for F in FL:
142
+ CurF = CurF.get(F, None)
143
+ if CurF is None:
144
+ return False
145
+ return True
146
+
147
+ def pythran_functor(func):
148
+ func = np_func_to_list(func)
149
+ submodules = "::".join(func[:-1] + ["functor"])
150
+ return "pythonic::numpy::%s::%s" % (submodules, func[-1])
151
+
152
+ def pythran_func_type(func, args):
153
+ args = ",".join(("std::declval<%s>()" % pythran_type(a.type) for a in args))
154
+ return "decltype(%s{}(%s))" % (pythran_functor(func), args)
155
+
156
+
157
+ @cython.ccall
158
+ def to_pythran(op, ptype=None):
159
+ op_type = op.type
160
+ if op_type.is_int:
161
+ # Make sure that integer literals always have exactly the type that the templates expect.
162
+ return op_type.cast_code(op.result())
163
+ if is_type(op_type, ["is_pythran_expr", "is_numeric", "is_float", "is_complex"]):
164
+ return op.result()
165
+ if op.is_none:
166
+ return "pythonic::%s::None" % pythran_builtins
167
+ if ptype is None:
168
+ ptype = pythran_type(op_type)
169
+
170
+ assert op.type.is_pyobject
171
+ return "from_python<%s>(%s)" % (ptype, op.py_result())
172
+
173
+
174
+ @cython.cfunc
175
+ def is_type(type_, types):
176
+ for attr in types:
177
+ if getattr(type_, attr, False):
178
+ return True
179
+ return False
180
+
181
+
182
+ def is_pythran_supported_node_or_none(node):
183
+ return node.is_none or is_pythran_supported_type(node.type)
184
+
185
+
186
+ @cython.ccall
187
+ def is_pythran_supported_type(type_):
188
+ pythran_supported = (
189
+ "is_pythran_expr", "is_int", "is_numeric", "is_float", "is_none", "is_complex")
190
+ return is_type(type_, pythran_supported) or is_pythran_expr(type_)
191
+
192
+
193
+ def is_pythran_supported_operation_type(type_):
194
+ pythran_supported = (
195
+ "is_pythran_expr", "is_int", "is_numeric", "is_float", "is_complex")
196
+ return is_type(type_,pythran_supported) or is_pythran_expr(type_)
197
+
198
+
199
+ @cython.ccall
200
+ def is_pythran_expr(type_):
201
+ return type_.is_pythran_expr
202
+
203
+
204
+ def is_pythran_buffer(type_):
205
+ return (type_.is_numpy_buffer and is_pythran_supported_dtype(type_.dtype) and
206
+ type_.mode in ("c", "strided") and not type_.cast)
207
+
208
+ def pythran_get_func_include_file(func):
209
+ func = np_func_to_list(func)
210
+ return "pythonic/numpy/%s.hpp" % "/".join(func)
211
+
212
+ def include_pythran_generic(env):
213
+ # Generic files
214
+ env.add_include_file("pythonic/core.hpp")
215
+ env.add_include_file("pythonic/python/core.hpp")
216
+ env.add_include_file("pythonic/types/bool.hpp")
217
+ env.add_include_file("pythonic/types/ndarray.hpp")
218
+ env.add_include_file("pythonic/numpy/power.hpp")
219
+ env.add_include_file("pythonic/%s/slice.hpp" % pythran_builtins)
220
+ env.add_include_file("<new>") # for placement new
221
+
222
+ for i in (8, 16, 32, 64):
223
+ env.add_include_file("pythonic/types/uint%d.hpp" % i)
224
+ env.add_include_file("pythonic/types/int%d.hpp" % i)
225
+ for t in ("float", "float32", "float64", "set", "slice", "tuple", "int",
226
+ "complex", "complex64", "complex128"):
227
+ env.add_include_file("pythonic/types/%s.hpp" % t)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Scanning.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: infer_types=True, language_level=3, auto_pickle=False
2
+ #
3
+ # Cython Scanner
4
+ #
5
+
6
+ from __future__ import absolute_import
7
+
8
+ import cython
9
+ cython.declare(make_lexicon=object, lexicon=object,
10
+ print_function=object, error=object, warning=object,
11
+ os=object, platform=object)
12
+
13
+ import os
14
+ import platform
15
+ from unicodedata import normalize
16
+ from contextlib import contextmanager
17
+
18
+ from .. import Utils
19
+ from ..Plex.Scanners import Scanner
20
+ from ..Plex.Errors import UnrecognizedInput
21
+ from .Errors import error, warning, hold_errors, release_errors, CompileError
22
+ from .Lexicon import any_string_prefix, make_lexicon, IDENT
23
+ from .Future import print_function
24
+
25
+ debug_scanner = 0
26
+ trace_scanner = 0
27
+ scanner_debug_flags = 0
28
+ scanner_dump_file = None
29
+
30
+ lexicon = None
31
+
32
+
33
+ def get_lexicon():
34
+ global lexicon
35
+ if not lexicon:
36
+ lexicon = make_lexicon()
37
+ return lexicon
38
+
39
+
40
+ #------------------------------------------------------------------
41
+
42
+ py_reserved_words = [
43
+ "global", "nonlocal", "def", "class", "print", "del", "pass", "break",
44
+ "continue", "return", "raise", "import", "exec", "try",
45
+ "except", "finally", "while", "if", "elif", "else", "for",
46
+ "in", "assert", "and", "or", "not", "is", "lambda",
47
+ "from", "yield", "with",
48
+ ]
49
+
50
+ pyx_reserved_words = py_reserved_words + [
51
+ "include", "ctypedef", "cdef", "cpdef",
52
+ "cimport", "DEF", "IF", "ELIF", "ELSE"
53
+ ]
54
+
55
+
56
+ #------------------------------------------------------------------
57
+
58
+ class CompileTimeScope(object):
59
+
60
+ def __init__(self, outer=None):
61
+ self.entries = {}
62
+ self.outer = outer
63
+
64
+ def declare(self, name, value):
65
+ self.entries[name] = value
66
+
67
+ def update(self, other):
68
+ self.entries.update(other)
69
+
70
+ def lookup_here(self, name):
71
+ return self.entries[name]
72
+
73
+ def __contains__(self, name):
74
+ return name in self.entries
75
+
76
+ def lookup(self, name):
77
+ try:
78
+ return self.lookup_here(name)
79
+ except KeyError:
80
+ outer = self.outer
81
+ if outer:
82
+ return outer.lookup(name)
83
+ else:
84
+ raise
85
+
86
+
87
+ def initial_compile_time_env():
88
+ benv = CompileTimeScope()
89
+ names = ('UNAME_SYSNAME', 'UNAME_NODENAME', 'UNAME_RELEASE', 'UNAME_VERSION', 'UNAME_MACHINE')
90
+ for name, value in zip(names, platform.uname()):
91
+ benv.declare(name, value)
92
+ try:
93
+ import __builtin__ as builtins
94
+ except ImportError:
95
+ import builtins
96
+
97
+ names = (
98
+ 'False', 'True',
99
+ 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes',
100
+ 'chr', 'cmp', 'complex', 'dict', 'divmod', 'enumerate', 'filter',
101
+ 'float', 'format', 'frozenset', 'hash', 'hex', 'int', 'len',
102
+ 'list', 'map', 'max', 'min', 'oct', 'ord', 'pow', 'range',
103
+ 'repr', 'reversed', 'round', 'set', 'slice', 'sorted', 'str',
104
+ 'sum', 'tuple', 'zip',
105
+ ### defined below in a platform independent way
106
+ # 'long', 'unicode', 'reduce', 'xrange'
107
+ )
108
+
109
+ for name in names:
110
+ try:
111
+ benv.declare(name, getattr(builtins, name))
112
+ except AttributeError:
113
+ # ignore, likely Py3
114
+ pass
115
+
116
+ # Py2/3 adaptations
117
+ from functools import reduce
118
+ benv.declare('reduce', reduce)
119
+ benv.declare('unicode', getattr(builtins, 'unicode', getattr(builtins, 'str')))
120
+ benv.declare('long', getattr(builtins, 'long', getattr(builtins, 'int')))
121
+ benv.declare('xrange', getattr(builtins, 'xrange', getattr(builtins, 'range')))
122
+
123
+ denv = CompileTimeScope(benv)
124
+ return denv
125
+
126
+
127
+ #------------------------------------------------------------------
128
+
129
+ class SourceDescriptor(object):
130
+ """
131
+ A SourceDescriptor should be considered immutable.
132
+ """
133
+ filename = None
134
+ in_utility_code = False
135
+
136
+ _file_type = 'pyx'
137
+
138
+ _escaped_description = None
139
+ _cmp_name = ''
140
+ def __str__(self):
141
+ assert False # To catch all places where a descriptor is used directly as a filename
142
+
143
+ def set_file_type_from_name(self, filename):
144
+ name, ext = os.path.splitext(filename)
145
+ self._file_type = ext in ('.pyx', '.pxd', '.py') and ext[1:] or 'pyx'
146
+
147
+ def is_cython_file(self):
148
+ return self._file_type in ('pyx', 'pxd')
149
+
150
+ def is_python_file(self):
151
+ return self._file_type == 'py'
152
+
153
+ def get_escaped_description(self):
154
+ if self._escaped_description is None:
155
+ esc_desc = \
156
+ self.get_description().encode('ASCII', 'replace').decode("ASCII")
157
+ # Use forward slashes on Windows since these paths
158
+ # will be used in the #line directives in the C/C++ files.
159
+ self._escaped_description = esc_desc.replace('\\', '/')
160
+ return self._escaped_description
161
+
162
+ def __gt__(self, other):
163
+ # this is only used to provide some sort of order
164
+ try:
165
+ return self._cmp_name > other._cmp_name
166
+ except AttributeError:
167
+ return False
168
+
169
+ def __lt__(self, other):
170
+ # this is only used to provide some sort of order
171
+ try:
172
+ return self._cmp_name < other._cmp_name
173
+ except AttributeError:
174
+ return False
175
+
176
+ def __le__(self, other):
177
+ # this is only used to provide some sort of order
178
+ try:
179
+ return self._cmp_name <= other._cmp_name
180
+ except AttributeError:
181
+ return False
182
+
183
+ def __copy__(self):
184
+ return self # immutable, no need to copy
185
+
186
+ def __deepcopy__(self, memo):
187
+ return self # immutable, no need to copy
188
+
189
+
190
+ class FileSourceDescriptor(SourceDescriptor):
191
+ """
192
+ Represents a code source. A code source is a more generic abstraction
193
+ for a "filename" (as sometimes the code doesn't come from a file).
194
+ Instances of code sources are passed to Scanner.__init__ as the
195
+ optional name argument and will be passed back when asking for
196
+ the position()-tuple.
197
+ """
198
+ def __init__(self, filename, path_description=None):
199
+ filename = Utils.decode_filename(filename)
200
+ self.path_description = path_description or filename
201
+ self.filename = filename
202
+ # Prefer relative paths to current directory (which is most likely the project root) over absolute paths.
203
+ workdir = os.path.abspath('.') + os.sep
204
+ self.file_path = filename[len(workdir):] if filename.startswith(workdir) else filename
205
+ self.set_file_type_from_name(filename)
206
+ self._cmp_name = filename
207
+ self._lines = {}
208
+
209
+ def get_lines(self, encoding=None, error_handling=None):
210
+ # we cache the lines only the second time this is called, in
211
+ # order to save memory when they are only used once
212
+ key = (encoding, error_handling)
213
+ try:
214
+ lines = self._lines[key]
215
+ if lines is not None:
216
+ return lines
217
+ except KeyError:
218
+ pass
219
+
220
+ with Utils.open_source_file(self.filename, encoding=encoding, error_handling=error_handling) as f:
221
+ lines = list(f)
222
+
223
+ if key in self._lines:
224
+ self._lines[key] = lines
225
+ else:
226
+ # do not cache the first access, but remember that we
227
+ # already read it once
228
+ self._lines[key] = None
229
+ return lines
230
+
231
+ def get_description(self):
232
+ try:
233
+ return os.path.relpath(self.path_description)
234
+ except ValueError:
235
+ # path not under current directory => use complete file path
236
+ return self.path_description
237
+
238
+ def get_error_description(self):
239
+ path = self.filename
240
+ cwd = Utils.decode_filename(os.getcwd() + os.path.sep)
241
+ if path.startswith(cwd):
242
+ return path[len(cwd):]
243
+ return path
244
+
245
+ def get_filenametable_entry(self):
246
+ return self.file_path
247
+
248
+ def __eq__(self, other):
249
+ return isinstance(other, FileSourceDescriptor) and self.filename == other.filename
250
+
251
+ def __hash__(self):
252
+ return hash(self.filename)
253
+
254
+ def __repr__(self):
255
+ return "<FileSourceDescriptor:%s>" % self.filename
256
+
257
+
258
+ class StringSourceDescriptor(SourceDescriptor):
259
+ """
260
+ Instances of this class can be used instead of a filenames if the
261
+ code originates from a string object.
262
+ """
263
+ def __init__(self, name, code):
264
+ self.name = name
265
+ #self.set_file_type_from_name(name)
266
+ self.codelines = [x + "\n" for x in code.split("\n")]
267
+ self._cmp_name = name
268
+
269
+ def get_lines(self, encoding=None, error_handling=None):
270
+ if not encoding:
271
+ return self.codelines
272
+ else:
273
+ return [line.encode(encoding, error_handling).decode(encoding)
274
+ for line in self.codelines]
275
+
276
+ def get_description(self):
277
+ return self.name
278
+
279
+ get_error_description = get_description
280
+
281
+ def get_filenametable_entry(self):
282
+ return "<stringsource>"
283
+
284
+ def __hash__(self):
285
+ return id(self)
286
+ # Do not hash on the name, an identical string source should be the
287
+ # same object (name is often defaulted in other places)
288
+ # return hash(self.name)
289
+
290
+ def __eq__(self, other):
291
+ return isinstance(other, StringSourceDescriptor) and self.name == other.name
292
+
293
+ def __repr__(self):
294
+ return "<StringSourceDescriptor:%s>" % self.name
295
+
296
+
297
+ #------------------------------------------------------------------
298
+
299
+ class PyrexScanner(Scanner):
300
+ # context Context Compilation context
301
+ # included_files [string] Files included with 'include' statement
302
+ # compile_time_env dict Environment for conditional compilation
303
+ # compile_time_eval boolean In a true conditional compilation context
304
+ # compile_time_expr boolean In a compile-time expression context
305
+ # put_back_on_failure list or None If set, this records states so the tentatively_scan
306
+ # contextmanager can restore it
307
+
308
+ def __init__(self, file, filename, parent_scanner=None,
309
+ scope=None, context=None, source_encoding=None, parse_comments=True, initial_pos=None):
310
+ Scanner.__init__(self, get_lexicon(), file, filename, initial_pos)
311
+
312
+ if filename.is_python_file():
313
+ self.in_python_file = True
314
+ keywords = py_reserved_words
315
+ else:
316
+ self.in_python_file = False
317
+ keywords = pyx_reserved_words
318
+ self.keywords = {keyword: keyword for keyword in keywords}
319
+
320
+ self.async_enabled = 0
321
+
322
+ if parent_scanner:
323
+ self.context = parent_scanner.context
324
+ self.included_files = parent_scanner.included_files
325
+ self.compile_time_env = parent_scanner.compile_time_env
326
+ self.compile_time_eval = parent_scanner.compile_time_eval
327
+ self.compile_time_expr = parent_scanner.compile_time_expr
328
+
329
+ if parent_scanner.async_enabled:
330
+ self.enter_async()
331
+ else:
332
+ self.context = context
333
+ self.included_files = scope.included_files
334
+ self.compile_time_env = initial_compile_time_env()
335
+ self.compile_time_eval = 1
336
+ self.compile_time_expr = 0
337
+ if getattr(context.options, 'compile_time_env', None):
338
+ self.compile_time_env.update(context.options.compile_time_env)
339
+ self.parse_comments = parse_comments
340
+ self.source_encoding = source_encoding
341
+ self.trace = trace_scanner
342
+ self.indentation_stack = [0]
343
+ self.indentation_char = None
344
+ self.bracket_nesting_level = 0
345
+
346
+ self.put_back_on_failure = None
347
+
348
+ self.begin('INDENT')
349
+ self.sy = ''
350
+ self.next()
351
+
352
+ def normalize_ident(self, text):
353
+ try:
354
+ text.encode('ascii') # really just name.isascii but supports Python 2 and 3
355
+ except UnicodeEncodeError:
356
+ text = normalize('NFKC', text)
357
+ self.produce(IDENT, text)
358
+
359
+ def commentline(self, text):
360
+ if self.parse_comments:
361
+ self.produce('commentline', text)
362
+
363
+ def strip_underscores(self, text, symbol):
364
+ self.produce(symbol, text.replace('_', ''))
365
+
366
+ def current_level(self):
367
+ return self.indentation_stack[-1]
368
+
369
+ def open_bracket_action(self, text):
370
+ self.bracket_nesting_level += 1
371
+ return text
372
+
373
+ def close_bracket_action(self, text):
374
+ self.bracket_nesting_level -= 1
375
+ return text
376
+
377
+ def newline_action(self, text):
378
+ if self.bracket_nesting_level == 0:
379
+ self.begin('INDENT')
380
+ self.produce('NEWLINE', '')
381
+
382
+ string_states = {
383
+ "'": 'SQ_STRING',
384
+ '"': 'DQ_STRING',
385
+ "'''": 'TSQ_STRING',
386
+ '"""': 'TDQ_STRING'
387
+ }
388
+
389
+ def begin_string_action(self, text):
390
+ while text[:1] in any_string_prefix:
391
+ text = text[1:]
392
+ self.begin(self.string_states[text])
393
+ self.produce('BEGIN_STRING')
394
+
395
+ def end_string_action(self, text):
396
+ self.begin('')
397
+ self.produce('END_STRING')
398
+
399
+ def unclosed_string_action(self, text):
400
+ self.end_string_action(text)
401
+ self.error_at_scanpos("Unclosed string literal")
402
+
403
+ def indentation_action(self, text):
404
+ self.begin('')
405
+ # Indentation within brackets should be ignored.
406
+ #if self.bracket_nesting_level > 0:
407
+ # return
408
+ # Check that tabs and spaces are being used consistently.
409
+ if text:
410
+ c = text[0]
411
+ #print "Scanner.indentation_action: indent with", repr(c) ###
412
+ if self.indentation_char is None:
413
+ self.indentation_char = c
414
+ #print "Scanner.indentation_action: setting indent_char to", repr(c)
415
+ else:
416
+ if self.indentation_char != c:
417
+ self.error_at_scanpos("Mixed use of tabs and spaces")
418
+ if text.replace(c, "") != "":
419
+ self.error_at_scanpos("Mixed use of tabs and spaces")
420
+ # Figure out how many indents/dedents to do
421
+ current_level = self.current_level()
422
+ new_level = len(text)
423
+ #print "Changing indent level from", current_level, "to", new_level ###
424
+ if new_level == current_level:
425
+ return
426
+ elif new_level > current_level:
427
+ #print "...pushing level", new_level ###
428
+ self.indentation_stack.append(new_level)
429
+ self.produce('INDENT', '')
430
+ else:
431
+ while new_level < self.current_level():
432
+ #print "...popping level", self.indentation_stack[-1] ###
433
+ self.indentation_stack.pop()
434
+ self.produce('DEDENT', '')
435
+ #print "...current level now", self.current_level() ###
436
+ if new_level != self.current_level():
437
+ self.error_at_scanpos("Inconsistent indentation")
438
+
439
+ def eof_action(self, text):
440
+ while len(self.indentation_stack) > 1:
441
+ self.produce('DEDENT', '')
442
+ self.indentation_stack.pop()
443
+ self.produce('EOF', '')
444
+
445
+ def next(self):
446
+ try:
447
+ sy, systring = self.read()
448
+ except UnrecognizedInput:
449
+ self.error_at_scanpos("Unrecognized character")
450
+ return # just a marker, error() always raises
451
+ if sy == IDENT:
452
+ if systring in self.keywords:
453
+ if systring == u'print' and print_function in self.context.future_directives:
454
+ self.keywords.pop('print', None)
455
+ elif systring == u'exec' and self.context.language_level >= 3:
456
+ self.keywords.pop('exec', None)
457
+ else:
458
+ sy = self.keywords[systring] # intern
459
+ systring = self.context.intern_ustring(systring)
460
+ if self.put_back_on_failure is not None:
461
+ self.put_back_on_failure.append((sy, systring, self.position()))
462
+ self.sy = sy
463
+ self.systring = systring
464
+ if False: # debug_scanner:
465
+ _, line, col = self.position()
466
+ if not self.systring or self.sy == self.systring:
467
+ t = self.sy
468
+ else:
469
+ t = "%s %s" % (self.sy, self.systring)
470
+ print("--- %3d %2d %s" % (line, col, t))
471
+
472
+ def peek(self):
473
+ saved = self.sy, self.systring
474
+ saved_pos = self.position()
475
+ self.next()
476
+ next = self.sy, self.systring
477
+ self.unread(self.sy, self.systring, self.position())
478
+ self.sy, self.systring = saved
479
+ self.last_token_position_tuple = saved_pos
480
+ return next
481
+
482
+ def put_back(self, sy, systring, pos):
483
+ self.unread(self.sy, self.systring, self.last_token_position_tuple)
484
+ self.sy = sy
485
+ self.systring = systring
486
+ self.last_token_position_tuple = pos
487
+
488
+
489
+ def error(self, message, pos=None, fatal=True):
490
+ if pos is None:
491
+ pos = self.position()
492
+ if self.sy == 'INDENT':
493
+ error(pos, "Possible inconsistent indentation")
494
+ err = error(pos, message)
495
+ if fatal: raise err
496
+
497
+ def error_at_scanpos(self, message):
498
+ # Like error(fatal=True), but gets the current scanning position rather than
499
+ # the position of the last token read.
500
+ pos = self.get_current_scan_pos()
501
+ self.error(message, pos, True)
502
+
503
+ def expect(self, what, message=None):
504
+ if self.sy == what:
505
+ self.next()
506
+ else:
507
+ self.expected(what, message)
508
+
509
+ def expect_keyword(self, what, message=None):
510
+ if self.sy == IDENT and self.systring == what:
511
+ self.next()
512
+ else:
513
+ self.expected(what, message)
514
+
515
+ def expected(self, what, message=None):
516
+ if message:
517
+ self.error(message)
518
+ else:
519
+ if self.sy == IDENT:
520
+ found = self.systring
521
+ else:
522
+ found = self.sy
523
+ self.error("Expected '%s', found '%s'" % (what, found))
524
+
525
+ def expect_indent(self):
526
+ self.expect('INDENT', "Expected an increase in indentation level")
527
+
528
+ def expect_dedent(self):
529
+ self.expect('DEDENT', "Expected a decrease in indentation level")
530
+
531
+ def expect_newline(self, message="Expected a newline", ignore_semicolon=False):
532
+ # Expect either a newline or end of file
533
+ useless_trailing_semicolon = None
534
+ if ignore_semicolon and self.sy == ';':
535
+ useless_trailing_semicolon = self.position()
536
+ self.next()
537
+ if self.sy != 'EOF':
538
+ self.expect('NEWLINE', message)
539
+ if useless_trailing_semicolon is not None:
540
+ warning(useless_trailing_semicolon, "useless trailing semicolon")
541
+
542
+ def enter_async(self):
543
+ self.async_enabled += 1
544
+ if self.async_enabled == 1:
545
+ self.keywords['async'] = 'async'
546
+ self.keywords['await'] = 'await'
547
+
548
+ def exit_async(self):
549
+ assert self.async_enabled > 0
550
+ self.async_enabled -= 1
551
+ if not self.async_enabled:
552
+ del self.keywords['await']
553
+ del self.keywords['async']
554
+ if self.sy in ('async', 'await'):
555
+ self.sy, self.systring = IDENT, self.context.intern_ustring(self.sy)
556
+
557
+ @contextmanager
558
+ @cython.locals(scanner=Scanner)
559
+ def tentatively_scan(scanner):
560
+ errors = hold_errors()
561
+ try:
562
+ put_back_on_failure = scanner.put_back_on_failure
563
+ scanner.put_back_on_failure = []
564
+ initial_state = (scanner.sy, scanner.systring, scanner.position())
565
+ try:
566
+ yield errors
567
+ except CompileError as e:
568
+ pass
569
+ finally:
570
+ if errors:
571
+ if scanner.put_back_on_failure:
572
+ for put_back in reversed(scanner.put_back_on_failure[:-1]):
573
+ scanner.put_back(*put_back)
574
+ # we need to restore the initial state too
575
+ scanner.put_back(*initial_state)
576
+ elif put_back_on_failure is not None:
577
+ # the outer "tentatively_scan" block that we're in might still
578
+ # want to undo this block
579
+ put_back_on_failure.extend(scanner.put_back_on_failure)
580
+ scanner.put_back_on_failure = put_back_on_failure
581
+ finally:
582
+ release_errors(ignore=True)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Symtab.py ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/TreeFragment.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # TreeFragments - parsing of strings to trees
3
+ #
4
+
5
+ """
6
+ Support for parsing strings into code trees.
7
+ """
8
+
9
+ from __future__ import absolute_import
10
+
11
+ import re
12
+ from io import StringIO
13
+
14
+ from .Scanning import PyrexScanner, StringSourceDescriptor
15
+ from .Symtab import ModuleScope
16
+ from . import PyrexTypes
17
+ from .Visitor import VisitorTransform
18
+ from .Nodes import Node, StatListNode
19
+ from .ExprNodes import NameNode
20
+ from .StringEncoding import _unicode
21
+ from . import Parsing
22
+ from . import Main
23
+ from . import UtilNodes
24
+
25
+
26
+ class StringParseContext(Main.Context):
27
+ def __init__(self, name, include_directories=None, compiler_directives=None, cpp=False):
28
+ if include_directories is None:
29
+ include_directories = []
30
+ if compiler_directives is None:
31
+ compiler_directives = {}
32
+ Main.Context.__init__(self, include_directories, compiler_directives, cpp=cpp, language_level='3str')
33
+ self.module_name = name
34
+
35
+ def find_module(self, module_name, from_module=None, pos=None, need_pxd=1, absolute_fallback=True, relative_import=False):
36
+ if module_name not in (self.module_name, 'cython'):
37
+ raise AssertionError("Not yet supporting any cimports/includes from string code snippets")
38
+ return ModuleScope(module_name, parent_module=None, context=self)
39
+
40
+
41
+ def parse_from_strings(name, code, pxds=None, level=None, initial_pos=None,
42
+ context=None, allow_struct_enum_decorator=False,
43
+ in_utility_code=False):
44
+ """
45
+ Utility method to parse a (unicode) string of code. This is mostly
46
+ used for internal Cython compiler purposes (creating code snippets
47
+ that transforms should emit, as well as unit testing).
48
+
49
+ code - a unicode string containing Cython (module-level) code
50
+ name - a descriptive name for the code source (to use in error messages etc.)
51
+ in_utility_code - used to suppress some messages from utility code. False by default
52
+ because some generated code snippets like properties and dataclasses
53
+ probably want to see those messages.
54
+
55
+ RETURNS
56
+
57
+ The tree, i.e. a ModuleNode. The ModuleNode's scope attribute is
58
+ set to the scope used when parsing.
59
+ """
60
+ if context is None:
61
+ context = StringParseContext(name)
62
+ # Since source files carry an encoding, it makes sense in this context
63
+ # to use a unicode string so that code fragments don't have to bother
64
+ # with encoding. This means that test code passed in should not have an
65
+ # encoding header.
66
+ assert isinstance(code, _unicode), "unicode code snippets only please"
67
+ encoding = "UTF-8"
68
+
69
+ module_name = name
70
+ if initial_pos is None:
71
+ initial_pos = (name, 1, 0)
72
+ code_source = StringSourceDescriptor(name, code)
73
+ if in_utility_code:
74
+ code_source.in_utility_code = True
75
+
76
+ scope = context.find_module(module_name, pos=initial_pos, need_pxd=False)
77
+
78
+ buf = StringIO(code)
79
+
80
+ scanner = PyrexScanner(buf, code_source, source_encoding = encoding,
81
+ scope = scope, context = context, initial_pos = initial_pos)
82
+ ctx = Parsing.Ctx(allow_struct_enum_decorator=allow_struct_enum_decorator)
83
+
84
+ if level is None:
85
+ tree = Parsing.p_module(scanner, 0, module_name, ctx=ctx)
86
+ tree.scope = scope
87
+ tree.is_pxd = False
88
+ else:
89
+ tree = Parsing.p_code(scanner, level=level, ctx=ctx)
90
+
91
+ tree.scope = scope
92
+ return tree
93
+
94
+
95
+ class TreeCopier(VisitorTransform):
96
+ def visit_Node(self, node):
97
+ if node is None:
98
+ return node
99
+ else:
100
+ c = node.clone_node()
101
+ self.visitchildren(c)
102
+ return c
103
+
104
+
105
+ class ApplyPositionAndCopy(TreeCopier):
106
+ def __init__(self, pos):
107
+ super(ApplyPositionAndCopy, self).__init__()
108
+ self.pos = pos
109
+
110
+ def visit_Node(self, node):
111
+ copy = super(ApplyPositionAndCopy, self).visit_Node(node)
112
+ copy.pos = self.pos
113
+ return copy
114
+
115
+
116
+ class TemplateTransform(VisitorTransform):
117
+ """
118
+ Makes a copy of a template tree while doing substitutions.
119
+
120
+ A dictionary "substitutions" should be passed in when calling
121
+ the transform; mapping names to replacement nodes. Then replacement
122
+ happens like this:
123
+ - If an ExprStatNode contains a single NameNode, whose name is
124
+ a key in the substitutions dictionary, the ExprStatNode is
125
+ replaced with a copy of the tree given in the dictionary.
126
+ It is the responsibility of the caller that the replacement
127
+ node is a valid statement.
128
+ - If a single NameNode is otherwise encountered, it is replaced
129
+ if its name is listed in the substitutions dictionary in the
130
+ same way. It is the responsibility of the caller to make sure
131
+ that the replacement nodes is a valid expression.
132
+
133
+ Also a list "temps" should be passed. Any names listed will
134
+ be transformed into anonymous, temporary names.
135
+
136
+ Currently supported for tempnames is:
137
+ NameNode
138
+ (various function and class definition nodes etc. should be added to this)
139
+
140
+ Each replacement node gets the position of the substituted node
141
+ recursively applied to every member node.
142
+ """
143
+
144
+ temp_name_counter = 0
145
+
146
+ def __call__(self, node, substitutions, temps, pos):
147
+ self.substitutions = substitutions
148
+ self.pos = pos
149
+ tempmap = {}
150
+ temphandles = []
151
+ for temp in temps:
152
+ TemplateTransform.temp_name_counter += 1
153
+ handle = UtilNodes.TempHandle(PyrexTypes.py_object_type)
154
+ tempmap[temp] = handle
155
+ temphandles.append(handle)
156
+ self.tempmap = tempmap
157
+ result = super(TemplateTransform, self).__call__(node)
158
+ if temps:
159
+ result = UtilNodes.TempsBlockNode(self.get_pos(node),
160
+ temps=temphandles,
161
+ body=result)
162
+ return result
163
+
164
+ def get_pos(self, node):
165
+ if self.pos:
166
+ return self.pos
167
+ else:
168
+ return node.pos
169
+
170
+ def visit_Node(self, node):
171
+ if node is None:
172
+ return None
173
+ else:
174
+ c = node.clone_node()
175
+ if self.pos is not None:
176
+ c.pos = self.pos
177
+ self.visitchildren(c)
178
+ return c
179
+
180
+ def try_substitution(self, node, key):
181
+ sub = self.substitutions.get(key)
182
+ if sub is not None:
183
+ pos = self.pos
184
+ if pos is None: pos = node.pos
185
+ return ApplyPositionAndCopy(pos)(sub)
186
+ else:
187
+ return self.visit_Node(node) # make copy as usual
188
+
189
+ def visit_NameNode(self, node):
190
+ temphandle = self.tempmap.get(node.name)
191
+ if temphandle:
192
+ # Replace name with temporary
193
+ return temphandle.ref(self.get_pos(node))
194
+ else:
195
+ return self.try_substitution(node, node.name)
196
+
197
+ def visit_ExprStatNode(self, node):
198
+ # If an expression-as-statement consists of only a replaceable
199
+ # NameNode, we replace the entire statement, not only the NameNode
200
+ if isinstance(node.expr, NameNode):
201
+ return self.try_substitution(node, node.expr.name)
202
+ else:
203
+ return self.visit_Node(node)
204
+
205
+
206
+ def copy_code_tree(node):
207
+ return TreeCopier()(node)
208
+
209
+
210
+ _match_indent = re.compile(u"^ *").match
211
+
212
+
213
+ def strip_common_indent(lines):
214
+ """Strips empty lines and common indentation from the list of strings given in lines"""
215
+ # TODO: Facilitate textwrap.indent instead
216
+ lines = [x for x in lines if x.strip() != u""]
217
+ if lines:
218
+ minindent = min([len(_match_indent(x).group(0)) for x in lines])
219
+ lines = [x[minindent:] for x in lines]
220
+ return lines
221
+
222
+
223
+ class TreeFragment(object):
224
+ def __init__(self, code, name=None, pxds=None, temps=None, pipeline=None, level=None, initial_pos=None):
225
+ if pxds is None:
226
+ pxds = {}
227
+ if temps is None:
228
+ temps = []
229
+ if pipeline is None:
230
+ pipeline = []
231
+ if not name:
232
+ name = "(tree fragment)"
233
+
234
+ if isinstance(code, _unicode):
235
+ def fmt(x): return u"\n".join(strip_common_indent(x.split(u"\n")))
236
+
237
+ fmt_code = fmt(code)
238
+ fmt_pxds = {}
239
+ for key, value in pxds.items():
240
+ fmt_pxds[key] = fmt(value)
241
+ mod = t = parse_from_strings(name, fmt_code, fmt_pxds, level=level, initial_pos=initial_pos)
242
+ if level is None:
243
+ t = t.body # Make sure a StatListNode is at the top
244
+ if not isinstance(t, StatListNode):
245
+ t = StatListNode(pos=mod.pos, stats=[t])
246
+ for transform in pipeline:
247
+ if transform is None:
248
+ continue
249
+ t = transform(t)
250
+ self.root = t
251
+ elif isinstance(code, Node):
252
+ if pxds:
253
+ raise NotImplementedError()
254
+ self.root = code
255
+ else:
256
+ raise ValueError("Unrecognized code format (accepts unicode and Node)")
257
+ self.temps = temps
258
+
259
+ def copy(self):
260
+ return copy_code_tree(self.root)
261
+
262
+ def substitute(self, nodes=None, temps=None, pos = None):
263
+ if nodes is None:
264
+ nodes = {}
265
+ if temps is None:
266
+ temps = []
267
+ return TemplateTransform()(self.root,
268
+ substitutions = nodes,
269
+ temps = self.temps + temps, pos = pos)
270
+
271
+
272
+ class SetPosTransform(VisitorTransform):
273
+ def __init__(self, pos):
274
+ super(SetPosTransform, self).__init__()
275
+ self.pos = pos
276
+
277
+ def visit_Node(self, node):
278
+ node.pos = self.pos
279
+ self.visitchildren(node)
280
+ return node
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/TypeInference.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from .Errors import error, message
4
+ from . import ExprNodes
5
+ from . import Nodes
6
+ from . import Builtin
7
+ from . import PyrexTypes
8
+ from .. import Utils
9
+ from .PyrexTypes import py_object_type, unspecified_type
10
+ from .Visitor import CythonTransform, EnvTransform
11
+
12
+ try:
13
+ reduce
14
+ except NameError:
15
+ from functools import reduce
16
+
17
+
18
+ class TypedExprNode(ExprNodes.ExprNode):
19
+ # Used for declaring assignments of a specified type without a known entry.
20
+ subexprs = []
21
+
22
+ def __init__(self, type, pos=None):
23
+ super(TypedExprNode, self).__init__(pos, type=type)
24
+
25
+ object_expr = TypedExprNode(py_object_type)
26
+
27
+
28
+ class MarkParallelAssignments(EnvTransform):
29
+ # Collects assignments inside parallel blocks prange, with parallel.
30
+ # Perhaps it's better to move it to ControlFlowAnalysis.
31
+
32
+ # tells us whether we're in a normal loop
33
+ in_loop = False
34
+
35
+ parallel_errors = False
36
+
37
+ def __init__(self, context):
38
+ # Track the parallel block scopes (with parallel, for i in prange())
39
+ self.parallel_block_stack = []
40
+ super(MarkParallelAssignments, self).__init__(context)
41
+
42
+ def mark_assignment(self, lhs, rhs, inplace_op=None):
43
+ if isinstance(lhs, (ExprNodes.NameNode, Nodes.PyArgDeclNode)):
44
+ if lhs.entry is None:
45
+ # TODO: This shouldn't happen...
46
+ return
47
+
48
+ if self.parallel_block_stack:
49
+ parallel_node = self.parallel_block_stack[-1]
50
+ previous_assignment = parallel_node.assignments.get(lhs.entry)
51
+
52
+ # If there was a previous assignment to the variable, keep the
53
+ # previous assignment position
54
+ if previous_assignment:
55
+ pos, previous_inplace_op = previous_assignment
56
+
57
+ if (inplace_op and previous_inplace_op and
58
+ inplace_op != previous_inplace_op):
59
+ # x += y; x *= y
60
+ t = (inplace_op, previous_inplace_op)
61
+ error(lhs.pos,
62
+ "Reduction operator '%s' is inconsistent "
63
+ "with previous reduction operator '%s'" % t)
64
+ else:
65
+ pos = lhs.pos
66
+
67
+ parallel_node.assignments[lhs.entry] = (pos, inplace_op)
68
+ parallel_node.assigned_nodes.append(lhs)
69
+
70
+ elif isinstance(lhs, ExprNodes.SequenceNode):
71
+ for i, arg in enumerate(lhs.args):
72
+ if not rhs or arg.is_starred:
73
+ item_node = None
74
+ else:
75
+ item_node = rhs.inferable_item_node(i)
76
+ self.mark_assignment(arg, item_node)
77
+ else:
78
+ # Could use this info to infer cdef class attributes...
79
+ pass
80
+
81
+ def visit_WithTargetAssignmentStatNode(self, node):
82
+ self.mark_assignment(node.lhs, node.with_node.enter_call)
83
+ self.visitchildren(node)
84
+ return node
85
+
86
+ def visit_SingleAssignmentNode(self, node):
87
+ self.mark_assignment(node.lhs, node.rhs)
88
+ self.visitchildren(node)
89
+ return node
90
+
91
+ def visit_CascadedAssignmentNode(self, node):
92
+ for lhs in node.lhs_list:
93
+ self.mark_assignment(lhs, node.rhs)
94
+ self.visitchildren(node)
95
+ return node
96
+
97
+ def visit_InPlaceAssignmentNode(self, node):
98
+ self.mark_assignment(node.lhs, node.create_binop_node(), node.operator)
99
+ self.visitchildren(node)
100
+ return node
101
+
102
+ def visit_ForInStatNode(self, node):
103
+ # TODO: Remove redundancy with range optimization...
104
+ is_special = False
105
+ sequence = node.iterator.sequence
106
+ target = node.target
107
+ iterator_scope = node.iterator.expr_scope or self.current_env()
108
+ if isinstance(sequence, ExprNodes.SimpleCallNode):
109
+ function = sequence.function
110
+ if sequence.self is None and function.is_name:
111
+ entry = iterator_scope.lookup(function.name)
112
+ if not entry or entry.is_builtin:
113
+ if function.name == 'reversed' and len(sequence.args) == 1:
114
+ sequence = sequence.args[0]
115
+ elif function.name == 'enumerate' and len(sequence.args) == 1:
116
+ if target.is_sequence_constructor and len(target.args) == 2:
117
+ iterator = sequence.args[0]
118
+ if iterator.is_name:
119
+ iterator_type = iterator.infer_type(iterator_scope)
120
+ if iterator_type.is_builtin_type:
121
+ # assume that builtin types have a length within Py_ssize_t
122
+ self.mark_assignment(
123
+ target.args[0],
124
+ ExprNodes.IntNode(target.pos, value='PY_SSIZE_T_MAX',
125
+ type=PyrexTypes.c_py_ssize_t_type))
126
+ target = target.args[1]
127
+ sequence = sequence.args[0]
128
+ if isinstance(sequence, ExprNodes.SimpleCallNode):
129
+ function = sequence.function
130
+ if sequence.self is None and function.is_name:
131
+ entry = iterator_scope.lookup(function.name)
132
+ if not entry or entry.is_builtin:
133
+ if function.name in ('range', 'xrange'):
134
+ is_special = True
135
+ for arg in sequence.args[:2]:
136
+ self.mark_assignment(target, arg)
137
+ if len(sequence.args) > 2:
138
+ self.mark_assignment(
139
+ target,
140
+ ExprNodes.binop_node(node.pos,
141
+ '+',
142
+ sequence.args[0],
143
+ sequence.args[2]))
144
+ if not is_special:
145
+ # A for-loop basically translates to subsequent calls to
146
+ # __getitem__(), so using an IndexNode here allows us to
147
+ # naturally infer the base type of pointers, C arrays,
148
+ # Python strings, etc., while correctly falling back to an
149
+ # object type when the base type cannot be handled.
150
+ self.mark_assignment(target, ExprNodes.IndexNode(
151
+ node.pos,
152
+ base=sequence,
153
+ index=ExprNodes.IntNode(target.pos, value='PY_SSIZE_T_MAX',
154
+ type=PyrexTypes.c_py_ssize_t_type)))
155
+
156
+ self.visitchildren(node)
157
+ return node
158
+
159
+ def visit_ForFromStatNode(self, node):
160
+ self.mark_assignment(node.target, node.bound1)
161
+ if node.step is not None:
162
+ self.mark_assignment(node.target,
163
+ ExprNodes.binop_node(node.pos,
164
+ '+',
165
+ node.bound1,
166
+ node.step))
167
+ self.visitchildren(node)
168
+ return node
169
+
170
+ def visit_WhileStatNode(self, node):
171
+ self.visitchildren(node)
172
+ return node
173
+
174
+ def visit_ExceptClauseNode(self, node):
175
+ if node.target is not None:
176
+ self.mark_assignment(node.target, object_expr)
177
+ self.visitchildren(node)
178
+ return node
179
+
180
+ def visit_FromCImportStatNode(self, node):
181
+ return node # Can't be assigned to...
182
+
183
+ def visit_FromImportStatNode(self, node):
184
+ for name, target in node.items:
185
+ if name != "*":
186
+ self.mark_assignment(target, object_expr)
187
+ self.visitchildren(node)
188
+ return node
189
+
190
+ def visit_DefNode(self, node):
191
+ # use fake expressions with the right result type
192
+ if node.star_arg:
193
+ self.mark_assignment(
194
+ node.star_arg, TypedExprNode(Builtin.tuple_type, node.pos))
195
+ if node.starstar_arg:
196
+ self.mark_assignment(
197
+ node.starstar_arg, TypedExprNode(Builtin.dict_type, node.pos))
198
+ EnvTransform.visit_FuncDefNode(self, node)
199
+ return node
200
+
201
+ def visit_DelStatNode(self, node):
202
+ for arg in node.args:
203
+ self.mark_assignment(arg, arg)
204
+ self.visitchildren(node)
205
+ return node
206
+
207
+ def visit_ParallelStatNode(self, node):
208
+ if self.parallel_block_stack:
209
+ node.parent = self.parallel_block_stack[-1]
210
+ else:
211
+ node.parent = None
212
+
213
+ nested = False
214
+ if node.is_prange:
215
+ if not node.parent:
216
+ node.is_parallel = True
217
+ else:
218
+ node.is_parallel = (node.parent.is_prange or not
219
+ node.parent.is_parallel)
220
+ nested = node.parent.is_prange
221
+ else:
222
+ node.is_parallel = True
223
+ # Note: nested with parallel() blocks are handled by
224
+ # ParallelRangeTransform!
225
+ # nested = node.parent
226
+ nested = node.parent and node.parent.is_prange
227
+
228
+ self.parallel_block_stack.append(node)
229
+
230
+ nested = nested or len(self.parallel_block_stack) > 2
231
+ if not self.parallel_errors and nested and not node.is_prange:
232
+ error(node.pos, "Only prange() may be nested")
233
+ self.parallel_errors = True
234
+
235
+ if node.is_prange:
236
+ self.visitchildren(node, attrs=('body', 'target', 'args'))
237
+
238
+ self.parallel_block_stack.pop()
239
+ if node.else_clause:
240
+ node.else_clause = self.visit(node.else_clause)
241
+ else:
242
+ self.visitchildren(node)
243
+ self.parallel_block_stack.pop()
244
+
245
+ self.parallel_errors = False
246
+ return node
247
+
248
+ def visit_YieldExprNode(self, node):
249
+ if self.parallel_block_stack:
250
+ error(node.pos, "'%s' not allowed in parallel sections" % node.expr_keyword)
251
+ return node
252
+
253
+ def visit_ReturnStatNode(self, node):
254
+ node.in_parallel = bool(self.parallel_block_stack)
255
+ return node
256
+
257
+
258
+ class MarkOverflowingArithmetic(CythonTransform):
259
+
260
+ # It may be possible to integrate this with the above for
261
+ # performance improvements (though likely not worth it).
262
+
263
+ might_overflow = False
264
+
265
+ def __call__(self, root):
266
+ self.env_stack = []
267
+ self.env = root.scope
268
+ return super(MarkOverflowingArithmetic, self).__call__(root)
269
+
270
+ def visit_safe_node(self, node):
271
+ self.might_overflow, saved = False, self.might_overflow
272
+ self.visitchildren(node)
273
+ self.might_overflow = saved
274
+ return node
275
+
276
+ def visit_neutral_node(self, node):
277
+ self.visitchildren(node)
278
+ return node
279
+
280
+ def visit_dangerous_node(self, node):
281
+ self.might_overflow, saved = True, self.might_overflow
282
+ self.visitchildren(node)
283
+ self.might_overflow = saved
284
+ return node
285
+
286
+ def visit_FuncDefNode(self, node):
287
+ self.env_stack.append(self.env)
288
+ self.env = node.local_scope
289
+ self.visit_safe_node(node)
290
+ self.env = self.env_stack.pop()
291
+ return node
292
+
293
+ def visit_NameNode(self, node):
294
+ if self.might_overflow:
295
+ entry = node.entry or self.env.lookup(node.name)
296
+ if entry:
297
+ entry.might_overflow = True
298
+ return node
299
+
300
+ def visit_BinopNode(self, node):
301
+ if node.operator in '&|^':
302
+ return self.visit_neutral_node(node)
303
+ else:
304
+ return self.visit_dangerous_node(node)
305
+
306
+ def visit_SimpleCallNode(self, node):
307
+ if node.function.is_name and node.function.name == 'abs':
308
+ # Overflows for minimum value of fixed size ints.
309
+ return self.visit_dangerous_node(node)
310
+ else:
311
+ return self.visit_neutral_node(node)
312
+
313
+ visit_UnopNode = visit_neutral_node
314
+
315
+ visit_UnaryMinusNode = visit_dangerous_node
316
+
317
+ visit_InPlaceAssignmentNode = visit_dangerous_node
318
+
319
+ visit_Node = visit_safe_node
320
+
321
+ def visit_assignment(self, lhs, rhs):
322
+ if (isinstance(rhs, ExprNodes.IntNode)
323
+ and isinstance(lhs, ExprNodes.NameNode)
324
+ and Utils.long_literal(rhs.value)):
325
+ entry = lhs.entry or self.env.lookup(lhs.name)
326
+ if entry:
327
+ entry.might_overflow = True
328
+
329
+ def visit_SingleAssignmentNode(self, node):
330
+ self.visit_assignment(node.lhs, node.rhs)
331
+ self.visitchildren(node)
332
+ return node
333
+
334
+ def visit_CascadedAssignmentNode(self, node):
335
+ for lhs in node.lhs_list:
336
+ self.visit_assignment(lhs, node.rhs)
337
+ self.visitchildren(node)
338
+ return node
339
+
340
+ class PyObjectTypeInferer(object):
341
+ """
342
+ If it's not declared, it's a PyObject.
343
+ """
344
+ def infer_types(self, scope):
345
+ """
346
+ Given a dict of entries, map all unspecified types to a specified type.
347
+ """
348
+ for name, entry in scope.entries.items():
349
+ if entry.type is unspecified_type:
350
+ entry.type = py_object_type
351
+
352
+ class SimpleAssignmentTypeInferer(object):
353
+ """
354
+ Very basic type inference.
355
+
356
+ Note: in order to support cross-closure type inference, this must be
357
+ applies to nested scopes in top-down order.
358
+ """
359
+ def set_entry_type(self, entry, entry_type, scope):
360
+ for e in entry.all_entries():
361
+ e.type = entry_type
362
+ if e.type.is_memoryviewslice:
363
+ # memoryview slices crash if they don't get initialized
364
+ e.init = e.type.default_value
365
+ if e.type.is_cpp_class:
366
+ if scope.directives['cpp_locals']:
367
+ e.make_cpp_optional()
368
+ else:
369
+ e.type.check_nullary_constructor(entry.pos)
370
+
371
+ def infer_types(self, scope):
372
+ enabled = scope.directives['infer_types']
373
+ verbose = scope.directives['infer_types.verbose']
374
+
375
+ if enabled == True:
376
+ spanning_type = aggressive_spanning_type
377
+ elif enabled is None: # safe mode
378
+ spanning_type = safe_spanning_type
379
+ else:
380
+ for entry in scope.entries.values():
381
+ if entry.type is unspecified_type:
382
+ self.set_entry_type(entry, py_object_type, scope)
383
+ return
384
+
385
+ # Set of assignments
386
+ assignments = set()
387
+ assmts_resolved = set()
388
+ dependencies = {}
389
+ assmt_to_names = {}
390
+
391
+ for name, entry in scope.entries.items():
392
+ for assmt in entry.cf_assignments:
393
+ names = assmt.type_dependencies()
394
+ assmt_to_names[assmt] = names
395
+ assmts = set()
396
+ for node in names:
397
+ assmts.update(node.cf_state)
398
+ dependencies[assmt] = assmts
399
+ if entry.type is unspecified_type:
400
+ assignments.update(entry.cf_assignments)
401
+ else:
402
+ assmts_resolved.update(entry.cf_assignments)
403
+
404
+ def infer_name_node_type(node):
405
+ types = [assmt.inferred_type for assmt in node.cf_state]
406
+ if not types:
407
+ node_type = py_object_type
408
+ else:
409
+ entry = node.entry
410
+ node_type = spanning_type(
411
+ types, entry.might_overflow, scope)
412
+ node.inferred_type = node_type
413
+
414
+ def infer_name_node_type_partial(node):
415
+ types = [assmt.inferred_type for assmt in node.cf_state
416
+ if assmt.inferred_type is not None]
417
+ if not types:
418
+ return
419
+ entry = node.entry
420
+ return spanning_type(types, entry.might_overflow, scope)
421
+
422
+ def inferred_types(entry):
423
+ has_none = False
424
+ has_pyobjects = False
425
+ types = []
426
+ for assmt in entry.cf_assignments:
427
+ if assmt.rhs.is_none:
428
+ has_none = True
429
+ else:
430
+ rhs_type = assmt.inferred_type
431
+ if rhs_type and rhs_type.is_pyobject:
432
+ has_pyobjects = True
433
+ types.append(rhs_type)
434
+ # Ignore None assignments as long as there are concrete Python type assignments.
435
+ # but include them if None is the only assigned Python object.
436
+ if has_none and not has_pyobjects:
437
+ types.append(py_object_type)
438
+ return types
439
+
440
+ def resolve_assignments(assignments):
441
+ resolved = set()
442
+ for assmt in assignments:
443
+ deps = dependencies[assmt]
444
+ # All assignments are resolved
445
+ if assmts_resolved.issuperset(deps):
446
+ for node in assmt_to_names[assmt]:
447
+ infer_name_node_type(node)
448
+ # Resolve assmt
449
+ inferred_type = assmt.infer_type()
450
+ assmts_resolved.add(assmt)
451
+ resolved.add(assmt)
452
+ assignments.difference_update(resolved)
453
+ return resolved
454
+
455
+ def partial_infer(assmt):
456
+ partial_types = []
457
+ for node in assmt_to_names[assmt]:
458
+ partial_type = infer_name_node_type_partial(node)
459
+ if partial_type is None:
460
+ return False
461
+ partial_types.append((node, partial_type))
462
+ for node, partial_type in partial_types:
463
+ node.inferred_type = partial_type
464
+ assmt.infer_type()
465
+ return True
466
+
467
+ partial_assmts = set()
468
+ def resolve_partial(assignments):
469
+ # try to handle circular references
470
+ partials = set()
471
+ for assmt in assignments:
472
+ if assmt in partial_assmts:
473
+ continue
474
+ if partial_infer(assmt):
475
+ partials.add(assmt)
476
+ assmts_resolved.add(assmt)
477
+ partial_assmts.update(partials)
478
+ return partials
479
+
480
+ # Infer assignments
481
+ while True:
482
+ if not resolve_assignments(assignments):
483
+ if not resolve_partial(assignments):
484
+ break
485
+ inferred = set()
486
+ # First pass
487
+ for entry in scope.entries.values():
488
+ if entry.type is not unspecified_type:
489
+ continue
490
+ entry_type = py_object_type
491
+ if assmts_resolved.issuperset(entry.cf_assignments):
492
+ types = inferred_types(entry)
493
+ if types and all(types):
494
+ entry_type = spanning_type(
495
+ types, entry.might_overflow, scope)
496
+ inferred.add(entry)
497
+ self.set_entry_type(entry, entry_type, scope)
498
+
499
+ def reinfer():
500
+ dirty = False
501
+ for entry in inferred:
502
+ for assmt in entry.cf_assignments:
503
+ assmt.infer_type()
504
+ types = inferred_types(entry)
505
+ new_type = spanning_type(types, entry.might_overflow, scope)
506
+ if new_type != entry.type:
507
+ self.set_entry_type(entry, new_type, scope)
508
+ dirty = True
509
+ return dirty
510
+
511
+ # types propagation
512
+ while reinfer():
513
+ pass
514
+
515
+ if verbose:
516
+ for entry in inferred:
517
+ message(entry.pos, "inferred '%s' to be of type '%s'" % (
518
+ entry.name, entry.type))
519
+
520
+
521
+ def find_spanning_type(type1, type2):
522
+ if type1 is type2:
523
+ result_type = type1
524
+ elif type1 is PyrexTypes.c_bint_type or type2 is PyrexTypes.c_bint_type:
525
+ # type inference can break the coercion back to a Python bool
526
+ # if it returns an arbitrary int type here
527
+ return py_object_type
528
+ else:
529
+ result_type = PyrexTypes.spanning_type(type1, type2)
530
+ if result_type in (PyrexTypes.c_double_type, PyrexTypes.c_float_type,
531
+ Builtin.float_type):
532
+ # Python's float type is just a C double, so it's safe to
533
+ # use the C type instead
534
+ return PyrexTypes.c_double_type
535
+ return result_type
536
+
537
+ def simply_type(result_type):
538
+ result_type = PyrexTypes.remove_cv_ref(result_type, remove_fakeref=True)
539
+ if result_type.is_array:
540
+ result_type = PyrexTypes.c_ptr_type(result_type.base_type)
541
+ return result_type
542
+
543
+ def aggressive_spanning_type(types, might_overflow, scope):
544
+ return simply_type(reduce(find_spanning_type, types))
545
+
546
+ def safe_spanning_type(types, might_overflow, scope):
547
+ result_type = simply_type(reduce(find_spanning_type, types))
548
+ if result_type.is_pyobject:
549
+ # In theory, any specific Python type is always safe to
550
+ # infer. However, inferring str can cause some existing code
551
+ # to break, since we are also now much more strict about
552
+ # coercion from str to char *. See trac #553.
553
+ if result_type.name == 'str':
554
+ return py_object_type
555
+ else:
556
+ return result_type
557
+ elif (result_type is PyrexTypes.c_double_type or
558
+ result_type is PyrexTypes.c_float_type):
559
+ # Python's float type is just a C double, so it's safe to use
560
+ # the C type instead. Similarly if given a C float, it leads to
561
+ # a small loss of precision vs Python but is otherwise the same
562
+ return result_type
563
+ elif result_type is PyrexTypes.c_bint_type:
564
+ # find_spanning_type() only returns 'bint' for clean boolean
565
+ # operations without other int types, so this is safe, too
566
+ return result_type
567
+ elif result_type.is_pythran_expr:
568
+ return result_type
569
+ elif result_type.is_ptr:
570
+ # Any pointer except (signed|unsigned|) char* can't implicitly
571
+ # become a PyObject, and inferring char* is now accepted, too.
572
+ return result_type
573
+ elif result_type.is_cpp_class:
574
+ # These can't implicitly become Python objects either.
575
+ return result_type
576
+ elif result_type.is_struct:
577
+ # Though we have struct -> object for some structs, this is uncommonly
578
+ # used, won't arise in pure Python, and there shouldn't be side
579
+ # effects, so I'm declaring this safe.
580
+ return result_type
581
+ elif result_type.is_memoryviewslice:
582
+ return result_type
583
+ elif result_type is PyrexTypes.soft_complex_type:
584
+ return result_type
585
+ elif result_type == PyrexTypes.c_double_complex_type:
586
+ return result_type
587
+ elif (result_type.is_int or result_type.is_enum) and not might_overflow:
588
+ return result_type
589
+ elif (not result_type.can_coerce_to_pyobject(scope)
590
+ and not result_type.is_error):
591
+ return result_type
592
+ return py_object_type
593
+
594
+
595
+ def get_type_inferer():
596
+ return SimpleAssignmentTypeInferer()
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/Visitor.pxd ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3str
2
+
3
+ cimport cython
4
+
5
+ cdef class TreeVisitor:
6
+ cdef public list access_path
7
+ cdef dict dispatch_table
8
+
9
+ cpdef visit(self, obj)
10
+ cdef _visit(self, obj)
11
+ cdef find_handler(self, obj)
12
+ cdef _visitchild(self, child, parent, attrname, idx)
13
+ cdef dict _visitchildren(self, parent, attrs, exclude)
14
+ cpdef visitchildren(self, parent, attrs=*, exclude=*)
15
+ cdef _raise_compiler_error(self, child, e)
16
+
17
+ cdef class VisitorTransform(TreeVisitor):
18
+ cdef dict _process_children(self, parent, attrs=*, exclude=*)
19
+ cpdef visitchildren(self, parent, attrs=*, exclude=*)
20
+ cdef list _flatten_list(self, list orig_list)
21
+ cpdef visitchild(self, parent, str attr, idx=*)
22
+
23
+ cdef class CythonTransform(VisitorTransform):
24
+ cdef public context
25
+ cdef public current_directives
26
+
27
+ cdef class ScopeTrackingTransform(CythonTransform):
28
+ cdef public scope_type
29
+ cdef public scope_node
30
+ cdef visit_scope(self, node, scope_type)
31
+
32
+ cdef class EnvTransform(CythonTransform):
33
+ cdef public list env_stack
34
+
35
+ cdef class MethodDispatcherTransform(EnvTransform):
36
+ @cython.final
37
+ cdef _visit_binop_node(self, node)
38
+ @cython.final
39
+ cdef _find_handler(self, match_name, bint has_kwargs)
40
+ @cython.final
41
+ cdef _delegate_to_assigned_value(self, node, function, arg_list, kwargs)
42
+ @cython.final
43
+ cdef _dispatch_to_handler(self, node, function, arg_list, kwargs)
44
+ @cython.final
45
+ cdef _dispatch_to_method_handler(self, attr_name, self_arg,
46
+ is_unbound_method, type_name,
47
+ node, function, arg_list, kwargs)
48
+
49
+ cdef class RecursiveNodeReplacer(VisitorTransform):
50
+ cdef public orig_node
51
+ cdef public new_node
52
+
53
+ cdef class NodeFinder(TreeVisitor):
54
+ cdef node
55
+ cdef public bint found
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Buffer.cpython-311.pyc ADDED
Binary file (41.8 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/FusedNode.cpython-311.pyc ADDED
Binary file (52.8 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Future.cpython-311.pyc ADDED
Binary file (982 Bytes). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Main.cpython-311.pyc ADDED
Binary file (38.8 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/MemoryView.cpython-311.pyc ADDED
Binary file (38.9 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/TreeFragment.cpython-311.pyc ADDED
Binary file (14.6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/TypeInference.cpython-311.pyc ADDED
Binary file (29.4 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/UtilNodes.cpython-311.pyc ADDED
Binary file (21.1 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Compiler/__pycache__/Visitor.cpython-311.pyc ADDED
Binary file (44.5 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/Lexicons.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python Lexical Analyser
3
+
4
+ Lexical Analyser Specification
5
+ """
6
+ from __future__ import absolute_import
7
+
8
+ from . import Actions
9
+ from . import DFA
10
+ from . import Errors
11
+ from . import Machines
12
+ from . import Regexps
13
+
14
+ # debug_flags for Lexicon constructor
15
+ DUMP_NFA = 1
16
+ DUMP_DFA = 2
17
+
18
+
19
+ class State(object):
20
+ """
21
+ This class is used as part of a Plex.Lexicon specification to
22
+ introduce a user-defined state.
23
+
24
+ Constructor:
25
+
26
+ State(name, token_specifications)
27
+ """
28
+
29
+ name = None
30
+ tokens = None
31
+
32
+ def __init__(self, name, tokens):
33
+ self.name = name
34
+ self.tokens = tokens
35
+
36
+
37
+ class Lexicon(object):
38
+ """
39
+ Lexicon(specification) builds a lexical analyser from the given
40
+ |specification|. The specification consists of a list of
41
+ specification items. Each specification item may be either:
42
+
43
+ 1) A token definition, which is a tuple:
44
+
45
+ (pattern, action)
46
+
47
+ The |pattern| is a regular axpression built using the
48
+ constructors defined in the Plex module.
49
+
50
+ The |action| is the action to be performed when this pattern
51
+ is recognised (see below).
52
+
53
+ 2) A state definition:
54
+
55
+ State(name, tokens)
56
+
57
+ where |name| is a character string naming the state,
58
+ and |tokens| is a list of token definitions as
59
+ above. The meaning and usage of states is described
60
+ below.
61
+
62
+ Actions
63
+ -------
64
+
65
+ The |action| in a token specification may be one of three things:
66
+
67
+ 1) A function, which is called as follows:
68
+
69
+ function(scanner, text)
70
+
71
+ where |scanner| is the relevant Scanner instance, and |text|
72
+ is the matched text. If the function returns anything
73
+ other than None, that value is returned as the value of the
74
+ token. If it returns None, scanning continues as if the IGNORE
75
+ action were specified (see below).
76
+
77
+ 2) One of the following special actions:
78
+
79
+ IGNORE means that the recognised characters will be treated as
80
+ white space and ignored. Scanning will continue until
81
+ the next non-ignored token is recognised before returning.
82
+
83
+ TEXT causes the scanned text itself to be returned as the
84
+ value of the token.
85
+
86
+ 3) Any other value, which is returned as the value of the token.
87
+
88
+ States
89
+ ------
90
+
91
+ At any given time, the scanner is in one of a number of states.
92
+ Associated with each state is a set of possible tokens. When scanning,
93
+ only tokens associated with the current state are recognised.
94
+
95
+ There is a default state, whose name is the empty string. Token
96
+ definitions which are not inside any State definition belong to
97
+ the default state.
98
+
99
+ The initial state of the scanner is the default state. The state can
100
+ be changed in one of two ways:
101
+
102
+ 1) Using Begin(state_name) as the action of a token.
103
+
104
+ 2) Calling the begin(state_name) method of the Scanner.
105
+
106
+ To change back to the default state, use '' as the state name.
107
+ """
108
+
109
+ machine = None # Machine
110
+ tables = None # StateTableMachine
111
+
112
+ def __init__(self, specifications, debug=None, debug_flags=7):
113
+ if not isinstance(specifications, list):
114
+ raise Errors.InvalidScanner("Scanner definition is not a list")
115
+
116
+ nfa = Machines.Machine()
117
+ default_initial_state = nfa.new_initial_state('')
118
+ token_number = 1
119
+
120
+ for spec in specifications:
121
+ if isinstance(spec, State):
122
+ user_initial_state = nfa.new_initial_state(spec.name)
123
+ for token in spec.tokens:
124
+ self.add_token_to_machine(
125
+ nfa, user_initial_state, token, token_number)
126
+ token_number += 1
127
+ elif isinstance(spec, tuple):
128
+ self.add_token_to_machine(
129
+ nfa, default_initial_state, spec, token_number)
130
+ token_number += 1
131
+ else:
132
+ raise Errors.InvalidToken(
133
+ token_number,
134
+ "Expected a token definition (tuple) or State instance")
135
+
136
+ if debug and (debug_flags & 1):
137
+ debug.write("\n============= NFA ===========\n")
138
+ nfa.dump(debug)
139
+
140
+ dfa = DFA.nfa_to_dfa(nfa, debug=(debug_flags & 3) == 3 and debug)
141
+
142
+ if debug and (debug_flags & 2):
143
+ debug.write("\n============= DFA ===========\n")
144
+ dfa.dump(debug)
145
+
146
+ self.machine = dfa
147
+
148
+ def add_token_to_machine(self, machine, initial_state, token_spec, token_number):
149
+ try:
150
+ (re, action_spec) = self.parse_token_definition(token_spec)
151
+ if isinstance(action_spec, Actions.Action):
152
+ action = action_spec
153
+ else:
154
+ try:
155
+ action_spec.__call__
156
+ except AttributeError:
157
+ action = Actions.Return(action_spec)
158
+ else:
159
+ action = Actions.Call(action_spec)
160
+ final_state = machine.new_state()
161
+ re.build_machine(machine, initial_state, final_state,
162
+ match_bol=1, nocase=0)
163
+ final_state.set_action(action, priority=-token_number)
164
+ except Errors.PlexError as e:
165
+ raise e.__class__("Token number %d: %s" % (token_number, e))
166
+
167
+ def parse_token_definition(self, token_spec):
168
+ if not isinstance(token_spec, tuple):
169
+ raise Errors.InvalidToken("Token definition is not a tuple")
170
+ if len(token_spec) != 2:
171
+ raise Errors.InvalidToken("Wrong number of items in token definition")
172
+
173
+ pattern, action = token_spec
174
+ if not isinstance(pattern, Regexps.RE):
175
+ raise Errors.InvalidToken("Pattern is not an RE instance")
176
+ return (pattern, action)
177
+
178
+ def get_initial_state(self, name):
179
+ return self.machine.get_initial_state(name)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/DFA.cpython-311.pyc ADDED
Binary file (6.63 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/Machines.cpython-311.pyc ADDED
Binary file (13.3 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Plex/__pycache__/Scanners.cpython-311.pyc ADDED
Binary file (12 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Builtins.c ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Special implementations of built-in functions and methods.
3
+ *
4
+ * Optional optimisations for builtins are in Optimize.c.
5
+ *
6
+ * General object operations and protocols are in ObjectHandling.c.
7
+ */
8
+
9
+ //////////////////// Globals.proto ////////////////////
10
+
11
+ static PyObject* __Pyx_Globals(void); /*proto*/
12
+
13
+ //////////////////// Globals ////////////////////
14
+ //@substitute: naming
15
+ //@requires: ObjectHandling.c::GetAttr
16
+
17
+ // This is a stub implementation until we have something more complete.
18
+ // Currently, we only handle the most common case of a read-only dict
19
+ // of Python names. Supporting cdef names in the module and write
20
+ // access requires a rewrite as a dedicated class.
21
+
22
+ static PyObject* __Pyx_Globals(void) {
23
+ return __Pyx_NewRef($moddict_cname);
24
+ }
25
+
26
+ //////////////////// PyExecGlobals.proto ////////////////////
27
+
28
+ static PyObject* __Pyx_PyExecGlobals(PyObject*);
29
+
30
+ //////////////////// PyExecGlobals ////////////////////
31
+ //@substitute: naming
32
+ //@requires: PyExec
33
+
34
+ static PyObject* __Pyx_PyExecGlobals(PyObject* code) {
35
+ return __Pyx_PyExec2(code, $moddict_cname);
36
+ }
37
+
38
+ //////////////////// PyExec.proto ////////////////////
39
+
40
+ static PyObject* __Pyx_PyExec3(PyObject*, PyObject*, PyObject*);
41
+ static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject*, PyObject*);
42
+
43
+ //////////////////// PyExec ////////////////////
44
+ //@substitute: naming
45
+
46
+ static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject* o, PyObject* globals) {
47
+ return __Pyx_PyExec3(o, globals, NULL);
48
+ }
49
+
50
+ static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) {
51
+ PyObject* result;
52
+ PyObject* s = 0;
53
+ char *code = 0;
54
+
55
+ if (!globals || globals == Py_None) {
56
+ globals = $moddict_cname;
57
+ } else if (unlikely(!PyDict_Check(globals))) {
58
+ __Pyx_TypeName globals_type_name =
59
+ __Pyx_PyType_GetName(Py_TYPE(globals));
60
+ PyErr_Format(PyExc_TypeError,
61
+ "exec() arg 2 must be a dict, not " __Pyx_FMT_TYPENAME,
62
+ globals_type_name);
63
+ __Pyx_DECREF_TypeName(globals_type_name);
64
+ goto bad;
65
+ }
66
+ if (!locals || locals == Py_None) {
67
+ locals = globals;
68
+ }
69
+
70
+ if (__Pyx_PyDict_GetItemStr(globals, PYIDENT("__builtins__")) == NULL) {
71
+ if (unlikely(PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0))
72
+ goto bad;
73
+ }
74
+
75
+ if (PyCode_Check(o)) {
76
+ if (unlikely(__Pyx_PyCode_HasFreeVars((PyCodeObject *)o))) {
77
+ PyErr_SetString(PyExc_TypeError,
78
+ "code object passed to exec() may not contain free variables");
79
+ goto bad;
80
+ }
81
+ #if PY_VERSION_HEX < 0x030200B1 || (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400)
82
+ result = PyEval_EvalCode((PyCodeObject *)o, globals, locals);
83
+ #else
84
+ result = PyEval_EvalCode(o, globals, locals);
85
+ #endif
86
+ } else {
87
+ PyCompilerFlags cf;
88
+ cf.cf_flags = 0;
89
+ #if PY_VERSION_HEX >= 0x030800A3
90
+ cf.cf_feature_version = PY_MINOR_VERSION;
91
+ #endif
92
+ if (PyUnicode_Check(o)) {
93
+ cf.cf_flags = PyCF_SOURCE_IS_UTF8;
94
+ s = PyUnicode_AsUTF8String(o);
95
+ if (unlikely(!s)) goto bad;
96
+ o = s;
97
+ #if PY_MAJOR_VERSION >= 3
98
+ } else if (unlikely(!PyBytes_Check(o))) {
99
+ #else
100
+ } else if (unlikely(!PyString_Check(o))) {
101
+ #endif
102
+ __Pyx_TypeName o_type_name = __Pyx_PyType_GetName(Py_TYPE(o));
103
+ PyErr_Format(PyExc_TypeError,
104
+ "exec: arg 1 must be string, bytes or code object, got " __Pyx_FMT_TYPENAME,
105
+ o_type_name);
106
+ __Pyx_DECREF_TypeName(o_type_name);
107
+ goto bad;
108
+ }
109
+ #if PY_MAJOR_VERSION >= 3
110
+ code = PyBytes_AS_STRING(o);
111
+ #else
112
+ code = PyString_AS_STRING(o);
113
+ #endif
114
+ if (PyEval_MergeCompilerFlags(&cf)) {
115
+ result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf);
116
+ } else {
117
+ result = PyRun_String(code, Py_file_input, globals, locals);
118
+ }
119
+ Py_XDECREF(s);
120
+ }
121
+
122
+ return result;
123
+ bad:
124
+ Py_XDECREF(s);
125
+ return 0;
126
+ }
127
+
128
+ //////////////////// GetAttr3.proto ////////////////////
129
+
130
+ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
131
+
132
+ //////////////////// GetAttr3 ////////////////////
133
+ //@requires: ObjectHandling.c::PyObjectGetAttrStr
134
+ //@requires: Exceptions.c::PyThreadStateGet
135
+ //@requires: Exceptions.c::PyErrFetchRestore
136
+ //@requires: Exceptions.c::PyErrExceptionMatches
137
+
138
+ #if __PYX_LIMITED_VERSION_HEX < 0x030d00A1
139
+ static PyObject *__Pyx_GetAttr3Default(PyObject *d) {
140
+ __Pyx_PyThreadState_declare
141
+ __Pyx_PyThreadState_assign
142
+ if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError)))
143
+ return NULL;
144
+ __Pyx_PyErr_Clear();
145
+ Py_INCREF(d);
146
+ return d;
147
+ }
148
+ #endif
149
+
150
+ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
151
+ PyObject *r;
152
+ #if __PYX_LIMITED_VERSION_HEX >= 0x030d00A1
153
+ int res = PyObject_GetOptionalAttr(o, n, &r);
154
+ // On failure (res == -1), r is set to NULL.
155
+ return (res != 0) ? r : __Pyx_NewRef(d);
156
+ #else
157
+ #if CYTHON_USE_TYPE_SLOTS
158
+ if (likely(PyString_Check(n))) {
159
+ r = __Pyx_PyObject_GetAttrStrNoError(o, n);
160
+ if (unlikely(!r) && likely(!PyErr_Occurred())) {
161
+ r = __Pyx_NewRef(d);
162
+ }
163
+ return r;
164
+ }
165
+ #endif
166
+ r = PyObject_GetAttr(o, n);
167
+ return (likely(r)) ? r : __Pyx_GetAttr3Default(d);
168
+ #endif
169
+ }
170
+
171
+ //////////////////// HasAttr.proto ////////////////////
172
+
173
+ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); /*proto*/
174
+
175
+ //////////////////// HasAttr ////////////////////
176
+ //@requires: ObjectHandling.c::GetAttr
177
+
178
+ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) {
179
+ PyObject *r;
180
+ if (unlikely(!__Pyx_PyBaseString_Check(n))) {
181
+ PyErr_SetString(PyExc_TypeError,
182
+ "hasattr(): attribute name must be string");
183
+ return -1;
184
+ }
185
+ r = __Pyx_GetAttr(o, n);
186
+ if (!r) {
187
+ PyErr_Clear();
188
+ return 0;
189
+ } else {
190
+ Py_DECREF(r);
191
+ return 1;
192
+ }
193
+ }
194
+
195
+ //////////////////// Intern.proto ////////////////////
196
+
197
+ static PyObject* __Pyx_Intern(PyObject* s); /* proto */
198
+
199
+ //////////////////// Intern ////////////////////
200
+ //@requires: ObjectHandling.c::RaiseUnexpectedTypeError
201
+
202
+ static PyObject* __Pyx_Intern(PyObject* s) {
203
+ if (unlikely(!PyString_CheckExact(s))) {
204
+ __Pyx_RaiseUnexpectedTypeError("str", s);
205
+ return NULL;
206
+ }
207
+ Py_INCREF(s);
208
+ #if PY_MAJOR_VERSION >= 3
209
+ PyUnicode_InternInPlace(&s);
210
+ #else
211
+ PyString_InternInPlace(&s);
212
+ #endif
213
+ return s;
214
+ }
215
+
216
+ //////////////////// abs_longlong.proto ////////////////////
217
+
218
+ static CYTHON_INLINE PY_LONG_LONG __Pyx_abs_longlong(PY_LONG_LONG x) {
219
+ #if defined (__cplusplus) && __cplusplus >= 201103L
220
+ return std::abs(x);
221
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
222
+ return llabs(x);
223
+ #elif defined (_MSC_VER)
224
+ // abs() is defined for long, but 64-bits type on MSVC is long long.
225
+ // Use MS-specific _abs64() instead, which returns the original (negative) value for abs(-MAX-1)
226
+ return _abs64(x);
227
+ #elif defined (__GNUC__)
228
+ // gcc or clang on 64 bit windows.
229
+ return __builtin_llabs(x);
230
+ #else
231
+ if (sizeof(PY_LONG_LONG) <= sizeof(Py_ssize_t))
232
+ return __Pyx_sst_abs(x);
233
+ return (x<0) ? -x : x;
234
+ #endif
235
+ }
236
+
237
+
238
+ //////////////////// py_abs.proto ////////////////////
239
+
240
+ #if CYTHON_USE_PYLONG_INTERNALS
241
+ static PyObject *__Pyx_PyLong_AbsNeg(PyObject *num);/*proto*/
242
+
243
+ #define __Pyx_PyNumber_Absolute(x) \
244
+ ((likely(PyLong_CheckExact(x))) ? \
245
+ (likely(__Pyx_PyLong_IsNonNeg(x)) ? (Py_INCREF(x), (x)) : __Pyx_PyLong_AbsNeg(x)) : \
246
+ PyNumber_Absolute(x))
247
+
248
+ #else
249
+ #define __Pyx_PyNumber_Absolute(x) PyNumber_Absolute(x)
250
+ #endif
251
+
252
+ //////////////////// py_abs ////////////////////
253
+
254
+ #if CYTHON_USE_PYLONG_INTERNALS
255
+ static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) {
256
+ #if PY_VERSION_HEX >= 0x030C00A7
257
+ if (likely(__Pyx_PyLong_IsCompact(n))) {
258
+ return PyLong_FromSize_t(__Pyx_PyLong_CompactValueUnsigned(n));
259
+ }
260
+ #else
261
+ if (likely(Py_SIZE(n) == -1)) {
262
+ // digits are unsigned
263
+ return PyLong_FromUnsignedLong(__Pyx_PyLong_Digits(n)[0]);
264
+ }
265
+ #endif
266
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000
267
+ {
268
+ PyObject *copy = _PyLong_Copy((PyLongObject*)n);
269
+ if (likely(copy)) {
270
+ #if PY_VERSION_HEX >= 0x030C00A7
271
+ // clear the sign bits to set the sign from SIGN_NEGATIVE (2) to positive (0)
272
+ ((PyLongObject*)copy)->long_value.lv_tag = ((PyLongObject*)copy)->long_value.lv_tag & ~_PyLong_SIGN_MASK;
273
+ #else
274
+ // negate the size to swap the sign
275
+ __Pyx_SET_SIZE(copy, -Py_SIZE(copy));
276
+ #endif
277
+ }
278
+ return copy;
279
+ }
280
+ #else
281
+ return PyNumber_Negative(n);
282
+ #endif
283
+ }
284
+ #endif
285
+
286
+
287
+ //////////////////// pow2.proto ////////////////////
288
+
289
+ #define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None)
290
+
291
+
292
+ //////////////////// int_pyucs4.proto ////////////////////
293
+
294
+ static CYTHON_INLINE int __Pyx_int_from_UCS4(Py_UCS4 uchar);
295
+
296
+ //////////////////// int_pyucs4 ////////////////////
297
+
298
+ static int __Pyx_int_from_UCS4(Py_UCS4 uchar) {
299
+ int digit = Py_UNICODE_TODIGIT(uchar);
300
+ if (unlikely(digit < 0)) {
301
+ PyErr_Format(PyExc_ValueError,
302
+ "invalid literal for int() with base 10: '%c'",
303
+ (int) uchar);
304
+ return -1;
305
+ }
306
+ return digit;
307
+ }
308
+
309
+
310
+ //////////////////// float_pyucs4.proto ////////////////////
311
+
312
+ static CYTHON_INLINE double __Pyx_double_from_UCS4(Py_UCS4 uchar);
313
+
314
+ //////////////////// float_pyucs4 ////////////////////
315
+
316
+ static double __Pyx_double_from_UCS4(Py_UCS4 uchar) {
317
+ double digit = Py_UNICODE_TONUMERIC(uchar);
318
+ if (unlikely(digit < 0.0)) {
319
+ PyErr_Format(PyExc_ValueError,
320
+ "could not convert string to float: '%c'",
321
+ (int) uchar);
322
+ return -1.0;
323
+ }
324
+ return digit;
325
+ }
326
+
327
+
328
+ //////////////////// object_ord.proto ////////////////////
329
+ //@requires: TypeConversion.c::UnicodeAsUCS4
330
+
331
+ #if PY_MAJOR_VERSION >= 3
332
+ #define __Pyx_PyObject_Ord(c) \
333
+ (likely(PyUnicode_Check(c)) ? (long)__Pyx_PyUnicode_AsPy_UCS4(c) : __Pyx__PyObject_Ord(c))
334
+ #else
335
+ #define __Pyx_PyObject_Ord(c) __Pyx__PyObject_Ord(c)
336
+ #endif
337
+ static long __Pyx__PyObject_Ord(PyObject* c); /*proto*/
338
+
339
+ //////////////////// object_ord ////////////////////
340
+
341
+ static long __Pyx__PyObject_Ord(PyObject* c) {
342
+ Py_ssize_t size;
343
+ if (PyBytes_Check(c)) {
344
+ size = PyBytes_GET_SIZE(c);
345
+ if (likely(size == 1)) {
346
+ return (unsigned char) PyBytes_AS_STRING(c)[0];
347
+ }
348
+ #if PY_MAJOR_VERSION < 3
349
+ } else if (PyUnicode_Check(c)) {
350
+ return (long)__Pyx_PyUnicode_AsPy_UCS4(c);
351
+ #endif
352
+ #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
353
+ } else if (PyByteArray_Check(c)) {
354
+ size = PyByteArray_GET_SIZE(c);
355
+ if (likely(size == 1)) {
356
+ return (unsigned char) PyByteArray_AS_STRING(c)[0];
357
+ }
358
+ #endif
359
+ } else {
360
+ // FIXME: support character buffers - but CPython doesn't support them either
361
+ __Pyx_TypeName c_type_name = __Pyx_PyType_GetName(Py_TYPE(c));
362
+ PyErr_Format(PyExc_TypeError,
363
+ "ord() expected string of length 1, but " __Pyx_FMT_TYPENAME " found",
364
+ c_type_name);
365
+ __Pyx_DECREF_TypeName(c_type_name);
366
+ return (long)(Py_UCS4)-1;
367
+ }
368
+ PyErr_Format(PyExc_TypeError,
369
+ "ord() expected a character, but string of length %zd found", size);
370
+ return (long)(Py_UCS4)-1;
371
+ }
372
+
373
+
374
+ //////////////////// py_dict_keys.proto ////////////////////
375
+
376
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d); /*proto*/
377
+
378
+ //////////////////// py_dict_keys ////////////////////
379
+
380
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d) {
381
+ if (PY_MAJOR_VERSION >= 3)
382
+ return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d);
383
+ else
384
+ return PyDict_Keys(d);
385
+ }
386
+
387
+ //////////////////// py_dict_values.proto ////////////////////
388
+
389
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); /*proto*/
390
+
391
+ //////////////////// py_dict_values ////////////////////
392
+
393
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) {
394
+ if (PY_MAJOR_VERSION >= 3)
395
+ return CALL_UNBOUND_METHOD(PyDict_Type, "values", d);
396
+ else
397
+ return PyDict_Values(d);
398
+ }
399
+
400
+ //////////////////// py_dict_items.proto ////////////////////
401
+
402
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); /*proto*/
403
+
404
+ //////////////////// py_dict_items ////////////////////
405
+
406
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) {
407
+ if (PY_MAJOR_VERSION >= 3)
408
+ return CALL_UNBOUND_METHOD(PyDict_Type, "items", d);
409
+ else
410
+ return PyDict_Items(d);
411
+ }
412
+
413
+ //////////////////// py_dict_iterkeys.proto ////////////////////
414
+
415
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d); /*proto*/
416
+
417
+ //////////////////// py_dict_iterkeys ////////////////////
418
+
419
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d) {
420
+ if (PY_MAJOR_VERSION >= 3)
421
+ return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d);
422
+ else
423
+ return CALL_UNBOUND_METHOD(PyDict_Type, "iterkeys", d);
424
+ }
425
+
426
+ //////////////////// py_dict_itervalues.proto ////////////////////
427
+
428
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d); /*proto*/
429
+
430
+ //////////////////// py_dict_itervalues ////////////////////
431
+
432
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d) {
433
+ if (PY_MAJOR_VERSION >= 3)
434
+ return CALL_UNBOUND_METHOD(PyDict_Type, "values", d);
435
+ else
436
+ return CALL_UNBOUND_METHOD(PyDict_Type, "itervalues", d);
437
+ }
438
+
439
+ //////////////////// py_dict_iteritems.proto ////////////////////
440
+
441
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d); /*proto*/
442
+
443
+ //////////////////// py_dict_iteritems ////////////////////
444
+
445
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d) {
446
+ if (PY_MAJOR_VERSION >= 3)
447
+ return CALL_UNBOUND_METHOD(PyDict_Type, "items", d);
448
+ else
449
+ return CALL_UNBOUND_METHOD(PyDict_Type, "iteritems", d);
450
+ }
451
+
452
+ //////////////////// py_dict_viewkeys.proto ////////////////////
453
+
454
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d); /*proto*/
455
+
456
+ //////////////////// py_dict_viewkeys ////////////////////
457
+
458
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d) {
459
+ if (PY_MAJOR_VERSION >= 3)
460
+ return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d);
461
+ else
462
+ return CALL_UNBOUND_METHOD(PyDict_Type, "viewkeys", d);
463
+ }
464
+
465
+ //////////////////// py_dict_viewvalues.proto ////////////////////
466
+
467
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d); /*proto*/
468
+
469
+ //////////////////// py_dict_viewvalues ////////////////////
470
+
471
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d) {
472
+ if (PY_MAJOR_VERSION >= 3)
473
+ return CALL_UNBOUND_METHOD(PyDict_Type, "values", d);
474
+ else
475
+ return CALL_UNBOUND_METHOD(PyDict_Type, "viewvalues", d);
476
+ }
477
+
478
+ //////////////////// py_dict_viewitems.proto ////////////////////
479
+
480
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d); /*proto*/
481
+
482
+ //////////////////// py_dict_viewitems ////////////////////
483
+
484
+ static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d) {
485
+ if (PY_MAJOR_VERSION >= 3)
486
+ return CALL_UNBOUND_METHOD(PyDict_Type, "items", d);
487
+ else
488
+ return CALL_UNBOUND_METHOD(PyDict_Type, "viewitems", d);
489
+ }
490
+
491
+
492
+ //////////////////// pyfrozenset_new.proto ////////////////////
493
+
494
+ static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it);
495
+
496
+ //////////////////// pyfrozenset_new ////////////////////
497
+ //@substitute: naming
498
+
499
+ static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) {
500
+ if (it) {
501
+ PyObject* result;
502
+ #if CYTHON_COMPILING_IN_PYPY
503
+ // PyPy currently lacks PyFrozenSet_CheckExact() and PyFrozenSet_New()
504
+ PyObject* args;
505
+ args = PyTuple_Pack(1, it);
506
+ if (unlikely(!args))
507
+ return NULL;
508
+ result = PyObject_Call((PyObject*)&PyFrozenSet_Type, args, NULL);
509
+ Py_DECREF(args);
510
+ return result;
511
+ #else
512
+ if (PyFrozenSet_CheckExact(it)) {
513
+ Py_INCREF(it);
514
+ return it;
515
+ }
516
+ result = PyFrozenSet_New(it);
517
+ if (unlikely(!result))
518
+ return NULL;
519
+ if ((PY_VERSION_HEX >= 0x031000A1) || likely(PySet_GET_SIZE(result)))
520
+ return result;
521
+ // empty frozenset is a singleton (on Python <3.10)
522
+ // seems wasteful, but CPython does the same
523
+ Py_DECREF(result);
524
+ #endif
525
+ }
526
+ #if CYTHON_USE_TYPE_SLOTS
527
+ return PyFrozenSet_Type.tp_new(&PyFrozenSet_Type, $empty_tuple, NULL);
528
+ #else
529
+ return PyObject_Call((PyObject*)&PyFrozenSet_Type, $empty_tuple, NULL);
530
+ #endif
531
+ }
532
+
533
+
534
+ //////////////////// PySet_Update.proto ////////////////////
535
+
536
+ static CYTHON_INLINE int __Pyx_PySet_Update(PyObject* set, PyObject* it); /*proto*/
537
+
538
+ //////////////////// PySet_Update ////////////////////
539
+
540
+ static CYTHON_INLINE int __Pyx_PySet_Update(PyObject* set, PyObject* it) {
541
+ PyObject *retval;
542
+ #if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY
543
+ if (PyAnySet_Check(it)) {
544
+ if (PySet_GET_SIZE(it) == 0)
545
+ return 0;
546
+ // fast and safe case: CPython will update our result set and return it
547
+ retval = PySet_Type.tp_as_number->nb_inplace_or(set, it);
548
+ if (likely(retval == set)) {
549
+ Py_DECREF(retval);
550
+ return 0;
551
+ }
552
+ if (unlikely(!retval))
553
+ return -1;
554
+ // unusual result, fall through to set.update() call below
555
+ Py_DECREF(retval);
556
+ }
557
+ #endif
558
+ retval = CALL_UNBOUND_METHOD(PySet_Type, "update", set, it);
559
+ if (unlikely(!retval)) return -1;
560
+ Py_DECREF(retval);
561
+ return 0;
562
+ }
563
+
564
+ ///////////////// memoryview_get_from_buffer.proto ////////////////////
565
+
566
+ // buffer is in limited api from Py3.11
567
+ #if !CYTHON_COMPILING_IN_LIMITED_API || CYTHON_LIMITED_API >= 0x030b0000
568
+ #define __Pyx_PyMemoryView_Get_{{name}}(o) PyMemoryView_GET_BUFFER(o)->{{name}}
569
+ #else
570
+ {{py:
571
+ out_types = dict(
572
+ ndim='int', readonly='int',
573
+ len='Py_ssize_t', itemsize='Py_ssize_t')
574
+ }} // can't get format like this unfortunately. It's unicode via getattr
575
+ {{py: out_type = out_types[name]}}
576
+ static {{out_type}} __Pyx_PyMemoryView_Get_{{name}}(PyObject *obj); /* proto */
577
+ #endif
578
+
579
+ ////////////// memoryview_get_from_buffer /////////////////////////
580
+
581
+ #if !CYTHON_COMPILING_IN_LIMITED_API || CYTHON_LIMITED_API >= 0x030b0000
582
+ #else
583
+ {{py:
584
+ out_types = dict(
585
+ ndim='int', readonly='int',
586
+ len='Py_ssize_t', itemsize='Py_ssize_t')
587
+ }}
588
+ {{py: out_type = out_types[name]}}
589
+ static {{out_type}} __Pyx_PyMemoryView_Get_{{name}}(PyObject *obj) {
590
+ {{out_type}} result;
591
+ PyObject *attr = PyObject_GetAttr(obj, PYIDENT("{{name}}"));
592
+ if (!attr) {
593
+ goto bad;
594
+ }
595
+ {{if out_type == 'int'}}
596
+ // I'm not worrying about overflow here because
597
+ // ultimately it comes from a C struct that's an int
598
+ result = PyLong_AsLong(attr);
599
+ {{elif out_type == 'Py_ssize_t'}}
600
+ result = PyLong_AsSsize_t(attr);
601
+ {{endif}}
602
+ Py_DECREF(attr);
603
+ return result;
604
+
605
+ bad:
606
+ Py_XDECREF(attr);
607
+ return -1;
608
+ }
609
+ #endif
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/CommonStructures.c ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////// FetchSharedCythonModule.proto ///////
2
+
3
+ static PyObject *__Pyx_FetchSharedCythonABIModule(void);
4
+
5
+ /////////////// FetchSharedCythonModule ////////////
6
+
7
+ static PyObject *__Pyx_FetchSharedCythonABIModule(void) {
8
+ return __Pyx_PyImport_AddModuleRef((char*) __PYX_ABI_MODULE_NAME);
9
+ }
10
+
11
+ /////////////// FetchCommonType.proto ///////////////
12
+
13
+ #if !CYTHON_USE_TYPE_SPECS
14
+ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type);
15
+ #else
16
+ static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases);
17
+ #endif
18
+
19
+ /////////////// FetchCommonType ///////////////
20
+ //@requires:ExtensionTypes.c::FixUpExtensionType
21
+ //@requires: FetchSharedCythonModule
22
+ //@requires:StringTools.c::IncludeStringH
23
+
24
+ static int __Pyx_VerifyCachedType(PyObject *cached_type,
25
+ const char *name,
26
+ Py_ssize_t basicsize,
27
+ Py_ssize_t expected_basicsize) {
28
+ if (!PyType_Check(cached_type)) {
29
+ PyErr_Format(PyExc_TypeError,
30
+ "Shared Cython type %.200s is not a type object", name);
31
+ return -1;
32
+ }
33
+ if (basicsize != expected_basicsize) {
34
+ PyErr_Format(PyExc_TypeError,
35
+ "Shared Cython type %.200s has the wrong size, try recompiling",
36
+ name);
37
+ return -1;
38
+ }
39
+ return 0;
40
+ }
41
+
42
+ #if !CYTHON_USE_TYPE_SPECS
43
+ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) {
44
+ PyObject* abi_module;
45
+ const char* object_name;
46
+ PyTypeObject *cached_type = NULL;
47
+
48
+ abi_module = __Pyx_FetchSharedCythonABIModule();
49
+ if (!abi_module) return NULL;
50
+ // get the final part of the object name (after the last dot)
51
+ object_name = strrchr(type->tp_name, '.');
52
+ object_name = object_name ? object_name+1 : type->tp_name;
53
+ cached_type = (PyTypeObject*) PyObject_GetAttrString(abi_module, object_name);
54
+ if (cached_type) {
55
+ if (__Pyx_VerifyCachedType(
56
+ (PyObject *)cached_type,
57
+ object_name,
58
+ cached_type->tp_basicsize,
59
+ type->tp_basicsize) < 0) {
60
+ goto bad;
61
+ }
62
+ goto done;
63
+ }
64
+
65
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad;
66
+ PyErr_Clear();
67
+ if (PyType_Ready(type) < 0) goto bad;
68
+ if (PyObject_SetAttrString(abi_module, object_name, (PyObject *)type) < 0)
69
+ goto bad;
70
+ Py_INCREF(type);
71
+ cached_type = type;
72
+
73
+ done:
74
+ Py_DECREF(abi_module);
75
+ // NOTE: always returns owned reference, or NULL on error
76
+ return cached_type;
77
+
78
+ bad:
79
+ Py_XDECREF(cached_type);
80
+ cached_type = NULL;
81
+ goto done;
82
+ }
83
+ #else
84
+
85
+ static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases) {
86
+ PyObject *abi_module, *cached_type = NULL;
87
+ // get the final part of the object name (after the last dot)
88
+ const char* object_name = strrchr(spec->name, '.');
89
+ object_name = object_name ? object_name+1 : spec->name;
90
+
91
+ abi_module = __Pyx_FetchSharedCythonABIModule();
92
+ if (!abi_module) return NULL;
93
+
94
+ cached_type = PyObject_GetAttrString(abi_module, object_name);
95
+ if (cached_type) {
96
+ Py_ssize_t basicsize;
97
+ #if CYTHON_COMPILING_IN_LIMITED_API
98
+ PyObject *py_basicsize;
99
+ py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__");
100
+ if (unlikely(!py_basicsize)) goto bad;
101
+ basicsize = PyLong_AsSsize_t(py_basicsize);
102
+ Py_DECREF(py_basicsize);
103
+ py_basicsize = 0;
104
+ if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad;
105
+ #else
106
+ basicsize = likely(PyType_Check(cached_type)) ? ((PyTypeObject*) cached_type)->tp_basicsize : -1;
107
+ #endif
108
+ if (__Pyx_VerifyCachedType(
109
+ cached_type,
110
+ object_name,
111
+ basicsize,
112
+ spec->basicsize) < 0) {
113
+ goto bad;
114
+ }
115
+ goto done;
116
+ }
117
+
118
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad;
119
+ PyErr_Clear();
120
+ // We pass the ABI module reference to avoid keeping the user module alive by foreign type usages.
121
+ CYTHON_UNUSED_VAR(module);
122
+ cached_type = __Pyx_PyType_FromModuleAndSpec(abi_module, spec, bases);
123
+ if (unlikely(!cached_type)) goto bad;
124
+ if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad;
125
+ if (PyObject_SetAttrString(abi_module, object_name, cached_type) < 0) goto bad;
126
+
127
+ done:
128
+ Py_DECREF(abi_module);
129
+ // NOTE: always returns owned reference, or NULL on error
130
+ assert(cached_type == NULL || PyType_Check(cached_type));
131
+ return (PyTypeObject *) cached_type;
132
+
133
+ bad:
134
+ Py_XDECREF(cached_type);
135
+ cached_type = NULL;
136
+ goto done;
137
+ }
138
+ #endif
139
+
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Coroutine.c ADDED
The diff for this file is too large to render. See raw diff
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/CppConvert.pyx ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO: Figure out how many of the pass-by-value copies the compiler can eliminate.
2
+
3
+
4
+ #################### string.from_py ####################
5
+
6
+ cdef extern from *:
7
+ cdef cppclass string "{{type}}":
8
+ string() except +
9
+ string(char* c_str, size_t size) except +
10
+ cdef const char* __Pyx_PyObject_AsStringAndSize(object, Py_ssize_t*) except NULL
11
+
12
+ @cname("{{cname}}")
13
+ cdef string {{cname}}(object o) except *:
14
+ cdef Py_ssize_t length = 0
15
+ cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length)
16
+ return string(data, length)
17
+
18
+
19
+ #################### string.to_py ####################
20
+
21
+ #cimport cython
22
+ #from libcpp.string cimport string
23
+ cdef extern from *:
24
+ cdef cppclass string "{{type}}":
25
+ char* data()
26
+ size_t size()
27
+
28
+ {{for py_type in ['PyObject', 'PyUnicode', 'PyStr', 'PyBytes', 'PyByteArray']}}
29
+ cdef extern from *:
30
+ cdef object __Pyx_{{py_type}}_FromStringAndSize(const char*, size_t)
31
+
32
+ @cname("{{cname.replace("PyObject", py_type, 1)}}")
33
+ cdef inline object {{cname.replace("PyObject", py_type, 1)}}(const string& s):
34
+ return __Pyx_{{py_type}}_FromStringAndSize(s.data(), s.size())
35
+ {{endfor}}
36
+
37
+
38
+ #################### vector.from_py ####################
39
+
40
+ cdef extern from *:
41
+ cdef cppclass vector "std::vector" [T]:
42
+ void push_back(T&) except +
43
+
44
+ @cname("{{cname}}")
45
+ cdef vector[X] {{cname}}(object o) except *:
46
+ cdef vector[X] v
47
+ for item in o:
48
+ v.push_back(<X>item)
49
+ return v
50
+
51
+
52
+ #################### vector.to_py ####################
53
+
54
+ cdef extern from *:
55
+ cdef cppclass vector "std::vector" [T]:
56
+ size_t size()
57
+ T& operator[](size_t)
58
+
59
+ cdef extern from "Python.h":
60
+ void Py_INCREF(object)
61
+ list PyList_New(Py_ssize_t size)
62
+ void PyList_SET_ITEM(object list, Py_ssize_t i, object o)
63
+ const Py_ssize_t PY_SSIZE_T_MAX
64
+
65
+ @cname("{{cname}}")
66
+ cdef object {{cname}}(const vector[X]& v):
67
+ if v.size() > <size_t> PY_SSIZE_T_MAX:
68
+ raise MemoryError()
69
+ v_size_signed = <Py_ssize_t> v.size()
70
+
71
+ o = PyList_New(v_size_signed)
72
+
73
+ cdef Py_ssize_t i
74
+ cdef object item
75
+
76
+ for i in range(v_size_signed):
77
+ item = v[i]
78
+ Py_INCREF(item)
79
+ PyList_SET_ITEM(o, i, item)
80
+
81
+ return o
82
+
83
+ #################### list.from_py ####################
84
+
85
+ cdef extern from *:
86
+ cdef cppclass cpp_list "std::list" [T]:
87
+ void push_back(T&) except +
88
+
89
+ @cname("{{cname}}")
90
+ cdef cpp_list[X] {{cname}}(object o) except *:
91
+ cdef cpp_list[X] l
92
+ for item in o:
93
+ l.push_back(<X>item)
94
+ return l
95
+
96
+
97
+ #################### list.to_py ####################
98
+
99
+ cimport cython
100
+
101
+ cdef extern from *:
102
+ cdef cppclass cpp_list "std::list" [T]:
103
+ cppclass const_iterator:
104
+ T& operator*()
105
+ const_iterator operator++()
106
+ bint operator!=(const_iterator)
107
+ const_iterator begin()
108
+ const_iterator end()
109
+ size_t size()
110
+
111
+ cdef extern from "Python.h":
112
+ void Py_INCREF(object)
113
+ list PyList_New(Py_ssize_t size)
114
+ void PyList_SET_ITEM(object list, Py_ssize_t i, object o)
115
+ cdef Py_ssize_t PY_SSIZE_T_MAX
116
+
117
+ @cname("{{cname}}")
118
+ cdef object {{cname}}(const cpp_list[X]& v):
119
+ if v.size() > <size_t> PY_SSIZE_T_MAX:
120
+ raise MemoryError()
121
+
122
+ o = PyList_New(<Py_ssize_t> v.size())
123
+
124
+ cdef object item
125
+ cdef Py_ssize_t i = 0
126
+ cdef cpp_list[X].const_iterator iter = v.begin()
127
+
128
+ while iter != v.end():
129
+ item = cython.operator.dereference(iter)
130
+ Py_INCREF(item)
131
+ PyList_SET_ITEM(o, i, item)
132
+ cython.operator.preincrement(iter)
133
+ i += 1
134
+
135
+ return o
136
+
137
+
138
+ #################### set.from_py ####################
139
+
140
+ cdef extern from *:
141
+ cdef cppclass set "std::{{maybe_unordered}}set" [T]:
142
+ void insert(T&) except +
143
+
144
+ @cname("{{cname}}")
145
+ cdef set[X] {{cname}}(object o) except *:
146
+ cdef set[X] s
147
+ for item in o:
148
+ s.insert(<X>item)
149
+ return s
150
+
151
+
152
+ #################### set.to_py ####################
153
+
154
+ cimport cython
155
+
156
+ cdef extern from *:
157
+ cdef cppclass cpp_set "std::{{maybe_unordered}}set" [T]:
158
+ cppclass const_iterator:
159
+ T& operator*()
160
+ const_iterator operator++()
161
+ bint operator!=(const_iterator)
162
+ const_iterator begin()
163
+ const_iterator end()
164
+
165
+ @cname("{{cname}}")
166
+ cdef object {{cname}}(const cpp_set[X]& s):
167
+ return {v for v in s}
168
+
169
+ #################### pair.from_py ####################
170
+
171
+ cdef extern from *:
172
+ cdef cppclass pair "std::pair" [T, U]:
173
+ pair() except +
174
+ pair(T&, U&) except +
175
+
176
+ @cname("{{cname}}")
177
+ cdef pair[X,Y] {{cname}}(object o) except *:
178
+ x, y = o
179
+ return pair[X,Y](<X>x, <Y>y)
180
+
181
+
182
+ #################### pair.to_py ####################
183
+
184
+ cdef extern from *:
185
+ cdef cppclass pair "std::pair" [T, U]:
186
+ T first
187
+ U second
188
+
189
+ @cname("{{cname}}")
190
+ cdef object {{cname}}(const pair[X,Y]& p):
191
+ return p.first, p.second
192
+
193
+
194
+ #################### map.from_py ####################
195
+
196
+ cdef extern from *:
197
+ cdef cppclass pair "std::pair" [T, U]:
198
+ pair(T&, U&) except +
199
+ cdef cppclass map "std::{{maybe_unordered}}map" [T, U]:
200
+ void insert(pair[T, U]&) except +
201
+ cdef cppclass vector "std::vector" [T]:
202
+ pass
203
+ int PY_MAJOR_VERSION
204
+
205
+
206
+ @cname("{{cname}}")
207
+ cdef map[X,Y] {{cname}}(object o) except *:
208
+ cdef map[X,Y] m
209
+ if PY_MAJOR_VERSION < 3:
210
+ for key, value in o.iteritems():
211
+ m.insert(pair[X,Y](<X>key, <Y>value))
212
+ else:
213
+ for key, value in o.items():
214
+ m.insert(pair[X,Y](<X>key, <Y>value))
215
+ return m
216
+
217
+
218
+ #################### map.to_py ####################
219
+ # TODO: Work out const so that this can take a const
220
+ # reference rather than pass by value.
221
+
222
+ cimport cython
223
+
224
+ cdef extern from *:
225
+ cdef cppclass map "std::{{maybe_unordered}}map" [T, U]:
226
+ cppclass value_type:
227
+ T first
228
+ U second
229
+ cppclass const_iterator:
230
+ value_type& operator*()
231
+ const_iterator operator++()
232
+ bint operator!=(const_iterator)
233
+ const_iterator begin()
234
+ const_iterator end()
235
+
236
+ @cname("{{cname}}")
237
+ cdef object {{cname}}(const map[X,Y]& s):
238
+ o = {}
239
+ cdef const map[X,Y].value_type *key_value
240
+ cdef map[X,Y].const_iterator iter = s.begin()
241
+ while iter != s.end():
242
+ key_value = &cython.operator.dereference(iter)
243
+ o[key_value.first] = key_value.second
244
+ cython.operator.preincrement(iter)
245
+ return o
246
+
247
+
248
+ #################### complex.from_py ####################
249
+
250
+ cdef extern from *:
251
+ cdef cppclass std_complex "std::complex" [T]:
252
+ std_complex()
253
+ std_complex(T, T) except +
254
+
255
+ @cname("{{cname}}")
256
+ cdef std_complex[X] {{cname}}(object o) except *:
257
+ cdef double complex z = o
258
+ return std_complex[X](<X>z.real, <X>z.imag)
259
+
260
+
261
+ #################### complex.to_py ####################
262
+
263
+ cdef extern from *:
264
+ cdef cppclass std_complex "std::complex" [T]:
265
+ X real()
266
+ X imag()
267
+
268
+ @cname("{{cname}}")
269
+ cdef object {{cname}}(const std_complex[X]& z):
270
+ cdef double complex tmp
271
+ tmp.real = <double>z.real()
272
+ tmp.imag = <double>z.imag()
273
+ return tmp
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/ExtensionTypes.c ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////// FixUpExtensionType.proto ///////////////
2
+
3
+ #if CYTHON_USE_TYPE_SPECS
4
+ static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); /*proto*/
5
+ #endif
6
+
7
+ /////////////// FixUpExtensionType ///////////////
8
+ //@requires:ModuleSetupCode.c::IncludeStructmemberH
9
+ //@requires:StringTools.c::IncludeStringH
10
+
11
+ #if CYTHON_USE_TYPE_SPECS
12
+ static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) {
13
+ #if PY_VERSION_HEX > 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API
14
+ CYTHON_UNUSED_VAR(spec);
15
+ CYTHON_UNUSED_VAR(type);
16
+ #else
17
+ // Set tp_weakreflist, tp_dictoffset, tp_vectorcalloffset
18
+ // Copied and adapted from https://bugs.python.org/issue38140
19
+ const PyType_Slot *slot = spec->slots;
20
+ while (slot && slot->slot && slot->slot != Py_tp_members)
21
+ slot++;
22
+ if (slot && slot->slot == Py_tp_members) {
23
+ int changed = 0;
24
+ #if !(PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON)
25
+ const
26
+ #endif
27
+ PyMemberDef *memb = (PyMemberDef*) slot->pfunc;
28
+ while (memb && memb->name) {
29
+ if (memb->name[0] == '_' && memb->name[1] == '_') {
30
+ #if PY_VERSION_HEX < 0x030900b1
31
+ if (strcmp(memb->name, "__weaklistoffset__") == 0) {
32
+ // The PyMemberDef must be a Py_ssize_t and readonly.
33
+ assert(memb->type == T_PYSSIZET);
34
+ assert(memb->flags == READONLY);
35
+ type->tp_weaklistoffset = memb->offset;
36
+ // FIXME: is it even worth calling PyType_Modified() here?
37
+ changed = 1;
38
+ }
39
+ else if (strcmp(memb->name, "__dictoffset__") == 0) {
40
+ // The PyMemberDef must be a Py_ssize_t and readonly.
41
+ assert(memb->type == T_PYSSIZET);
42
+ assert(memb->flags == READONLY);
43
+ type->tp_dictoffset = memb->offset;
44
+ // FIXME: is it even worth calling PyType_Modified() here?
45
+ changed = 1;
46
+ }
47
+ #if CYTHON_METH_FASTCALL
48
+ else if (strcmp(memb->name, "__vectorcalloffset__") == 0) {
49
+ // The PyMemberDef must be a Py_ssize_t and readonly.
50
+ assert(memb->type == T_PYSSIZET);
51
+ assert(memb->flags == READONLY);
52
+ #if PY_VERSION_HEX >= 0x030800b4
53
+ type->tp_vectorcall_offset = memb->offset;
54
+ #else
55
+ type->tp_print = (printfunc) memb->offset;
56
+ #endif
57
+ // FIXME: is it even worth calling PyType_Modified() here?
58
+ changed = 1;
59
+ }
60
+ #endif
61
+ #else
62
+ if ((0));
63
+ #endif
64
+ #if PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON
65
+ else if (strcmp(memb->name, "__module__") == 0) {
66
+ // PyType_FromSpec() in CPython <= 3.9b1 overwrites this field with a constant string.
67
+ // See https://bugs.python.org/issue40703
68
+ PyObject *descr;
69
+ // The PyMemberDef must be an object and normally readable, possibly writable.
70
+ assert(memb->type == T_OBJECT);
71
+ assert(memb->flags == 0 || memb->flags == READONLY);
72
+ descr = PyDescr_NewMember(type, memb);
73
+ if (unlikely(!descr))
74
+ return -1;
75
+ if (unlikely(PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr) < 0)) {
76
+ Py_DECREF(descr);
77
+ return -1;
78
+ }
79
+ Py_DECREF(descr);
80
+ changed = 1;
81
+ }
82
+ #endif
83
+ }
84
+ memb++;
85
+ }
86
+ if (changed)
87
+ PyType_Modified(type);
88
+ }
89
+ #endif
90
+ return 0;
91
+ }
92
+ #endif
93
+
94
+
95
+ /////////////// ValidateBasesTuple.proto ///////////////
96
+
97
+ #if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS
98
+ static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); /*proto*/
99
+ #endif
100
+
101
+ /////////////// ValidateBasesTuple ///////////////
102
+
103
+ #if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS
104
+ static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) {
105
+ // Loop over all bases (except the first) and check that those
106
+ // really are heap types. Otherwise, it would not be safe to
107
+ // subclass them.
108
+ //
109
+ // We also check tp_dictoffset: it is unsafe to inherit
110
+ // tp_dictoffset from a base class because the object structures
111
+ // would not be compatible. So, if our extension type doesn't set
112
+ // tp_dictoffset (i.e. there is no __dict__ attribute in the object
113
+ // structure), we need to check that none of the base classes sets
114
+ // it either.
115
+ Py_ssize_t i, n;
116
+ #if CYTHON_ASSUME_SAFE_MACROS
117
+ n = PyTuple_GET_SIZE(bases);
118
+ #else
119
+ n = PyTuple_Size(bases);
120
+ if (n < 0) return -1;
121
+ #endif
122
+ for (i = 1; i < n; i++) /* Skip first base */
123
+ {
124
+ #if CYTHON_AVOID_BORROWED_REFS
125
+ PyObject *b0 = PySequence_GetItem(bases, i);
126
+ if (!b0) return -1;
127
+ #elif CYTHON_ASSUME_SAFE_MACROS
128
+ PyObject *b0 = PyTuple_GET_ITEM(bases, i);
129
+ #else
130
+ PyObject *b0 = PyTuple_GetItem(bases, i);
131
+ if (!b0) return -1;
132
+ #endif
133
+ PyTypeObject *b;
134
+ #if PY_MAJOR_VERSION < 3
135
+ /* Disallow old-style classes */
136
+ if (PyClass_Check(b0))
137
+ {
138
+ PyErr_Format(PyExc_TypeError, "base class '%.200s' is an old-style class",
139
+ PyString_AS_STRING(((PyClassObject*)b0)->cl_name));
140
+ #if CYTHON_AVOID_BORROWED_REFS
141
+ Py_DECREF(b0);
142
+ #endif
143
+ return -1;
144
+ }
145
+ #endif
146
+ b = (PyTypeObject*) b0;
147
+ if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE))
148
+ {
149
+ __Pyx_TypeName b_name = __Pyx_PyType_GetName(b);
150
+ PyErr_Format(PyExc_TypeError,
151
+ "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name);
152
+ __Pyx_DECREF_TypeName(b_name);
153
+ #if CYTHON_AVOID_BORROWED_REFS
154
+ Py_DECREF(b0);
155
+ #endif
156
+ return -1;
157
+ }
158
+ if (dictoffset == 0)
159
+ {
160
+ Py_ssize_t b_dictoffset = 0;
161
+ #if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY
162
+ b_dictoffset = b->tp_dictoffset;
163
+ #else
164
+ PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__");
165
+ if (!py_b_dictoffset) goto dictoffset_return;
166
+ b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset);
167
+ Py_DECREF(py_b_dictoffset);
168
+ if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return;
169
+ #endif
170
+ if (b_dictoffset) {
171
+ {
172
+ __Pyx_TypeName b_name = __Pyx_PyType_GetName(b);
173
+ PyErr_Format(PyExc_TypeError,
174
+ "extension type '%.200s' has no __dict__ slot, "
175
+ "but base type '" __Pyx_FMT_TYPENAME "' has: "
176
+ "either add 'cdef dict __dict__' to the extension type "
177
+ "or add '__slots__ = [...]' to the base type",
178
+ type_name, b_name);
179
+ __Pyx_DECREF_TypeName(b_name);
180
+ }
181
+ #if !(CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY)
182
+ dictoffset_return:
183
+ #endif
184
+ #if CYTHON_AVOID_BORROWED_REFS
185
+ Py_DECREF(b0);
186
+ #endif
187
+ return -1;
188
+ }
189
+ }
190
+ #if CYTHON_AVOID_BORROWED_REFS
191
+ Py_DECREF(b0);
192
+ #endif
193
+ }
194
+ return 0;
195
+ }
196
+ #endif
197
+
198
+
199
+ /////////////// PyType_Ready.proto ///////////////
200
+
201
+ // unused when using type specs
202
+ CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t);/*proto*/
203
+
204
+ /////////////// PyType_Ready ///////////////
205
+ //@requires: ObjectHandling.c::PyObjectCallMethod0
206
+ //@requires: ValidateBasesTuple
207
+
208
+ // Wrapper around PyType_Ready() with some runtime checks and fixes
209
+ // to deal with multiple inheritance.
210
+ static int __Pyx_PyType_Ready(PyTypeObject *t) {
211
+
212
+ // FIXME: is this really suitable for CYTHON_COMPILING_IN_LIMITED_API?
213
+ #if CYTHON_USE_TYPE_SPECS || !(CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API) || defined(PYSTON_MAJOR_VERSION)
214
+ // avoid C warning about unused helper function
215
+ (void)__Pyx_PyObject_CallMethod0;
216
+ #if CYTHON_USE_TYPE_SPECS
217
+ (void)__Pyx_validate_bases_tuple;
218
+ #endif
219
+
220
+ return PyType_Ready(t);
221
+
222
+ #else
223
+ int r;
224
+ PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*);
225
+ if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1))
226
+ return -1;
227
+
228
+ #if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION)
229
+ {
230
+ // Make sure GC does not pick up our non-heap type as heap type with this hack!
231
+ // For details, see https://github.com/cython/cython/issues/3603
232
+ int gc_was_enabled;
233
+ #if PY_VERSION_HEX >= 0x030A00b1
234
+ // finally added in Py3.10 :)
235
+ gc_was_enabled = PyGC_Disable();
236
+ (void)__Pyx_PyObject_CallMethod0;
237
+
238
+ #else
239
+ // Call gc.disable() as a backwards compatible fallback, but only if needed.
240
+ PyObject *ret, *py_status;
241
+ PyObject *gc = NULL;
242
+ #if PY_VERSION_HEX >= 0x030700a1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400)
243
+ // https://foss.heptapod.net/pypy/pypy/-/issues/3385
244
+ gc = PyImport_GetModule(PYUNICODE("gc"));
245
+ #endif
246
+ if (unlikely(!gc)) gc = PyImport_Import(PYUNICODE("gc"));
247
+ if (unlikely(!gc)) return -1;
248
+ py_status = __Pyx_PyObject_CallMethod0(gc, PYUNICODE("isenabled"));
249
+ if (unlikely(!py_status)) {
250
+ Py_DECREF(gc);
251
+ return -1;
252
+ }
253
+ gc_was_enabled = __Pyx_PyObject_IsTrue(py_status);
254
+ Py_DECREF(py_status);
255
+ if (gc_was_enabled > 0) {
256
+ ret = __Pyx_PyObject_CallMethod0(gc, PYUNICODE("disable"));
257
+ if (unlikely(!ret)) {
258
+ Py_DECREF(gc);
259
+ return -1;
260
+ }
261
+ Py_DECREF(ret);
262
+ } else if (unlikely(gc_was_enabled == -1)) {
263
+ Py_DECREF(gc);
264
+ return -1;
265
+ }
266
+ #endif
267
+
268
+ // As of https://bugs.python.org/issue22079
269
+ // PyType_Ready enforces that all bases of a non-heap type are
270
+ // non-heap. We know that this is the case for the solid base but
271
+ // other bases are heap allocated and are kept alive through the
272
+ // tp_bases reference.
273
+ // Other than this check, the Py_TPFLAGS_HEAPTYPE flag is unused
274
+ // in PyType_Ready().
275
+ t->tp_flags |= Py_TPFLAGS_HEAPTYPE;
276
+ #if PY_VERSION_HEX >= 0x030A0000
277
+ // As of https://github.com/python/cpython/pull/25520
278
+ // PyType_Ready marks types as immutable if they are static types
279
+ // and requires the Py_TPFLAGS_IMMUTABLETYPE flag to mark types as
280
+ // immutable
281
+ // Manually set the Py_TPFLAGS_IMMUTABLETYPE flag, since the type
282
+ // is immutable
283
+ t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE;
284
+ #endif
285
+ #else
286
+ // avoid C warning about unused helper function
287
+ (void)__Pyx_PyObject_CallMethod0;
288
+ #endif
289
+
290
+ r = PyType_Ready(t);
291
+
292
+ #if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION)
293
+ t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
294
+
295
+ #if PY_VERSION_HEX >= 0x030A00b1
296
+ if (gc_was_enabled)
297
+ PyGC_Enable();
298
+ #else
299
+ if (gc_was_enabled) {
300
+ PyObject *tp, *v, *tb;
301
+ PyErr_Fetch(&tp, &v, &tb);
302
+ ret = __Pyx_PyObject_CallMethod0(gc, PYUNICODE("enable"));
303
+ if (likely(ret || r == -1)) {
304
+ Py_XDECREF(ret);
305
+ // do not overwrite exceptions raised by PyType_Ready() above
306
+ PyErr_Restore(tp, v, tb);
307
+ } else {
308
+ // PyType_Ready() succeeded, but gc.enable() failed.
309
+ Py_XDECREF(tp);
310
+ Py_XDECREF(v);
311
+ Py_XDECREF(tb);
312
+ r = -1;
313
+ }
314
+ }
315
+ Py_DECREF(gc);
316
+ #endif
317
+ }
318
+ #endif
319
+
320
+ return r;
321
+ #endif
322
+ }
323
+
324
+
325
+ /////////////// PyTrashcan.proto ///////////////
326
+
327
+ // These macros are taken from https://github.com/python/cpython/pull/11841
328
+ // Unlike the Py_TRASHCAN_SAFE_BEGIN/Py_TRASHCAN_SAFE_END macros, they
329
+ // allow dealing correctly with subclasses.
330
+
331
+ // This requires CPython version >= 2.7.4
332
+ // (or >= 3.2.4 but we don't support such old Python 3 versions anyway)
333
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03080000
334
+ // https://github.com/python/cpython/pull/11841 merged so Cython reimplementation
335
+ // is no longer necessary
336
+ #define __Pyx_TRASHCAN_BEGIN Py_TRASHCAN_BEGIN
337
+ #define __Pyx_TRASHCAN_END Py_TRASHCAN_END
338
+ #elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02070400
339
+ #define __Pyx_TRASHCAN_BEGIN_CONDITION(op, cond) \
340
+ do { \
341
+ PyThreadState *_tstate = NULL; \
342
+ // If "cond" is false, then _tstate remains NULL and the deallocator
343
+ // is run normally without involving the trashcan
344
+ if (cond) { \
345
+ _tstate = PyThreadState_GET(); \
346
+ if (_tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) { \
347
+ // Store the object (to be deallocated later) and jump past
348
+ // Py_TRASHCAN_END, skipping the body of the deallocator
349
+ _PyTrash_thread_deposit_object((PyObject*)(op)); \
350
+ break; \
351
+ } \
352
+ ++_tstate->trash_delete_nesting; \
353
+ }
354
+ // The body of the deallocator is here.
355
+ #define __Pyx_TRASHCAN_END \
356
+ if (_tstate) { \
357
+ --_tstate->trash_delete_nesting; \
358
+ if (_tstate->trash_delete_later && _tstate->trash_delete_nesting <= 0) \
359
+ _PyTrash_thread_destroy_chain(); \
360
+ } \
361
+ } while (0);
362
+
363
+ #define __Pyx_TRASHCAN_BEGIN(op, dealloc) __Pyx_TRASHCAN_BEGIN_CONDITION(op, \
364
+ __Pyx_PyObject_GetSlot(op, tp_dealloc, destructor) == (destructor)(dealloc))
365
+
366
+ #else
367
+ // The trashcan is a no-op on other Python implementations
368
+ // or old CPython versions
369
+ #define __Pyx_TRASHCAN_BEGIN(op, dealloc)
370
+ #define __Pyx_TRASHCAN_END
371
+ #endif
372
+
373
+ /////////////// CallNextTpDealloc.proto ///////////////
374
+
375
+ static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc);
376
+
377
+ /////////////// CallNextTpDealloc ///////////////
378
+
379
+ static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) {
380
+ PyTypeObject* type = Py_TYPE(obj);
381
+ destructor tp_dealloc = NULL;
382
+ /* try to find the first parent type that has a different tp_dealloc() function */
383
+ while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc)
384
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
385
+ while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc)
386
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
387
+ if (type)
388
+ tp_dealloc(obj);
389
+ }
390
+
391
+ /////////////// CallNextTpTraverse.proto ///////////////
392
+
393
+ static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse);
394
+
395
+ /////////////// CallNextTpTraverse ///////////////
396
+
397
+ static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) {
398
+ PyTypeObject* type = Py_TYPE(obj);
399
+ traverseproc tp_traverse = NULL;
400
+ /* try to find the first parent type that has a different tp_traverse() function */
401
+ while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse)
402
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
403
+ while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse)
404
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
405
+ if (type && tp_traverse)
406
+ return tp_traverse(obj, v, a);
407
+ // FIXME: really ignore?
408
+ return 0;
409
+ }
410
+
411
+ /////////////// CallNextTpClear.proto ///////////////
412
+
413
+ static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear);
414
+
415
+ /////////////// CallNextTpClear ///////////////
416
+
417
+ static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) {
418
+ PyTypeObject* type = Py_TYPE(obj);
419
+ inquiry tp_clear = NULL;
420
+ /* try to find the first parent type that has a different tp_clear() function */
421
+ while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear)
422
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
423
+ while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear)
424
+ type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*);
425
+ if (type && tp_clear)
426
+ tp_clear(obj);
427
+ }
428
+
429
+ /////////////// SetupReduce.proto ///////////////
430
+
431
+ #if !CYTHON_COMPILING_IN_LIMITED_API
432
+ static int __Pyx_setup_reduce(PyObject* type_obj);
433
+ #endif
434
+
435
+ /////////////// SetupReduce ///////////////
436
+ //@requires: ObjectHandling.c::PyObjectGetAttrStrNoError
437
+ //@requires: ObjectHandling.c::PyObjectGetAttrStr
438
+ //@substitute: naming
439
+
440
+ #if !CYTHON_COMPILING_IN_LIMITED_API
441
+ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) {
442
+ int ret;
443
+ PyObject *name_attr;
444
+
445
+ name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, PYIDENT("__name__"));
446
+ if (likely(name_attr)) {
447
+ ret = PyObject_RichCompareBool(name_attr, name, Py_EQ);
448
+ } else {
449
+ ret = -1;
450
+ }
451
+
452
+ if (unlikely(ret < 0)) {
453
+ PyErr_Clear();
454
+ ret = 0;
455
+ }
456
+
457
+ Py_XDECREF(name_attr);
458
+ return ret;
459
+ }
460
+
461
+ static int __Pyx_setup_reduce(PyObject* type_obj) {
462
+ int ret = 0;
463
+ PyObject *object_reduce = NULL;
464
+ PyObject *object_getstate = NULL;
465
+ PyObject *object_reduce_ex = NULL;
466
+ PyObject *reduce = NULL;
467
+ PyObject *reduce_ex = NULL;
468
+ PyObject *reduce_cython = NULL;
469
+ PyObject *setstate = NULL;
470
+ PyObject *setstate_cython = NULL;
471
+ PyObject *getstate = NULL;
472
+
473
+ #if CYTHON_USE_PYTYPE_LOOKUP
474
+ getstate = _PyType_Lookup((PyTypeObject*)type_obj, PYIDENT("__getstate__"));
475
+ #else
476
+ getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, PYIDENT("__getstate__"));
477
+ if (!getstate && PyErr_Occurred()) {
478
+ goto __PYX_BAD;
479
+ }
480
+ #endif
481
+ if (getstate) {
482
+ // Python 3.11 introduces object.__getstate__. Because it's version-specific failure to find it should not be an error
483
+ #if CYTHON_USE_PYTYPE_LOOKUP
484
+ object_getstate = _PyType_Lookup(&PyBaseObject_Type, PYIDENT("__getstate__"));
485
+ #else
486
+ object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, PYIDENT("__getstate__"));
487
+ if (!object_getstate && PyErr_Occurred()) {
488
+ goto __PYX_BAD;
489
+ }
490
+ #endif
491
+ if (object_getstate != getstate) {
492
+ goto __PYX_GOOD;
493
+ }
494
+ }
495
+
496
+ #if CYTHON_USE_PYTYPE_LOOKUP
497
+ object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, PYIDENT("__reduce_ex__")); if (!object_reduce_ex) goto __PYX_BAD;
498
+ #else
499
+ object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, PYIDENT("__reduce_ex__")); if (!object_reduce_ex) goto __PYX_BAD;
500
+ #endif
501
+
502
+ reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, PYIDENT("__reduce_ex__")); if (unlikely(!reduce_ex)) goto __PYX_BAD;
503
+ if (reduce_ex == object_reduce_ex) {
504
+
505
+ #if CYTHON_USE_PYTYPE_LOOKUP
506
+ object_reduce = _PyType_Lookup(&PyBaseObject_Type, PYIDENT("__reduce__")); if (!object_reduce) goto __PYX_BAD;
507
+ #else
508
+ object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, PYIDENT("__reduce__")); if (!object_reduce) goto __PYX_BAD;
509
+ #endif
510
+ reduce = __Pyx_PyObject_GetAttrStr(type_obj, PYIDENT("__reduce__")); if (unlikely(!reduce)) goto __PYX_BAD;
511
+
512
+ if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, PYIDENT("__reduce_cython__"))) {
513
+ reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, PYIDENT("__reduce_cython__"));
514
+ if (likely(reduce_cython)) {
515
+ ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, PYIDENT("__reduce__"), reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD;
516
+ ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, PYIDENT("__reduce_cython__")); if (unlikely(ret < 0)) goto __PYX_BAD;
517
+ } else if (reduce == object_reduce || PyErr_Occurred()) {
518
+ // Ignore if we're done, i.e. if 'reduce' already has the right name and the original is gone.
519
+ // Otherwise: error.
520
+ goto __PYX_BAD;
521
+ }
522
+
523
+ setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, PYIDENT("__setstate__"));
524
+ if (!setstate) PyErr_Clear();
525
+ if (!setstate || __Pyx_setup_reduce_is_named(setstate, PYIDENT("__setstate_cython__"))) {
526
+ setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, PYIDENT("__setstate_cython__"));
527
+ if (likely(setstate_cython)) {
528
+ ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, PYIDENT("__setstate__"), setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD;
529
+ ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, PYIDENT("__setstate_cython__")); if (unlikely(ret < 0)) goto __PYX_BAD;
530
+ } else if (!setstate || PyErr_Occurred()) {
531
+ // Ignore if we're done, i.e. if 'setstate' already has the right name and the original is gone.
532
+ // Otherwise: error.
533
+ goto __PYX_BAD;
534
+ }
535
+ }
536
+ PyType_Modified((PyTypeObject*)type_obj);
537
+ }
538
+ }
539
+ goto __PYX_GOOD;
540
+
541
+ __PYX_BAD:
542
+ if (!PyErr_Occurred()) {
543
+ __Pyx_TypeName type_obj_name =
544
+ __Pyx_PyType_GetName((PyTypeObject*)type_obj);
545
+ PyErr_Format(PyExc_RuntimeError,
546
+ "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name);
547
+ __Pyx_DECREF_TypeName(type_obj_name);
548
+ }
549
+ ret = -1;
550
+ __PYX_GOOD:
551
+ #if !CYTHON_USE_PYTYPE_LOOKUP
552
+ Py_XDECREF(object_reduce);
553
+ Py_XDECREF(object_reduce_ex);
554
+ Py_XDECREF(object_getstate);
555
+ Py_XDECREF(getstate);
556
+ #endif
557
+ Py_XDECREF(reduce);
558
+ Py_XDECREF(reduce_ex);
559
+ Py_XDECREF(reduce_cython);
560
+ Py_XDECREF(setstate);
561
+ Py_XDECREF(setstate_cython);
562
+ return ret;
563
+ }
564
+ #endif
565
+
566
+
567
+ /////////////// BinopSlot ///////////////
568
+
569
+ static CYTHON_INLINE PyObject *{{func_name}}_maybe_call_slot(PyTypeObject* type, PyObject *left, PyObject *right {{extra_arg_decl}}) {
570
+ {{slot_type}} slot;
571
+ #if CYTHON_USE_TYPE_SLOTS || PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY
572
+ slot = type->tp_as_number ? type->tp_as_number->{{slot_name}} : NULL;
573
+ #else
574
+ slot = ({{slot_type}}) PyType_GetSlot(type, Py_{{slot_name}});
575
+ #endif
576
+ return slot ? slot(left, right {{extra_arg}}) : __Pyx_NewRef(Py_NotImplemented);
577
+ }
578
+
579
+ static PyObject *{{func_name}}(PyObject *left, PyObject *right {{extra_arg_decl}}) {
580
+ int maybe_self_is_left, maybe_self_is_right = 0;
581
+ maybe_self_is_left = Py_TYPE(left) == Py_TYPE(right)
582
+ #if CYTHON_USE_TYPE_SLOTS
583
+ || (Py_TYPE(left)->tp_as_number && Py_TYPE(left)->tp_as_number->{{slot_name}} == &{{func_name}})
584
+ #endif
585
+ || __Pyx_TypeCheck(left, {{type_cname}});
586
+
587
+ // Optimize for the common case where the left operation is defined (and successful).
588
+ {{if not overloads_left}}
589
+ maybe_self_is_right = Py_TYPE(left) == Py_TYPE(right)
590
+ #if CYTHON_USE_TYPE_SLOTS
591
+ || (Py_TYPE(right)->tp_as_number && Py_TYPE(right)->tp_as_number->{{slot_name}} == &{{func_name}})
592
+ #endif
593
+ || __Pyx_TypeCheck(right, {{type_cname}});
594
+ {{endif}}
595
+
596
+ if (maybe_self_is_left) {
597
+ PyObject *res;
598
+
599
+ {{if overloads_right and not overloads_left}}
600
+ if (maybe_self_is_right) {
601
+ res = {{call_right}};
602
+ if (res != Py_NotImplemented) return res;
603
+ Py_DECREF(res);
604
+ // Don't bother calling it again.
605
+ maybe_self_is_right = 0;
606
+ }
607
+ {{endif}}
608
+
609
+ res = {{call_left}};
610
+ if (res != Py_NotImplemented) return res;
611
+ Py_DECREF(res);
612
+ }
613
+
614
+ {{if overloads_left}}
615
+ maybe_self_is_right = Py_TYPE(left) == Py_TYPE(right)
616
+ #if CYTHON_USE_TYPE_SLOTS
617
+ || (Py_TYPE(right)->tp_as_number && Py_TYPE(right)->tp_as_number->{{slot_name}} == &{{func_name}})
618
+ #endif
619
+ || PyType_IsSubtype(Py_TYPE(right), {{type_cname}});
620
+ {{endif}}
621
+
622
+ if (maybe_self_is_right) {
623
+ return {{call_right}};
624
+ }
625
+ return __Pyx_NewRef(Py_NotImplemented);
626
+ }
627
+
628
+ /////////////// ValidateExternBase.proto ///////////////
629
+
630
+ static int __Pyx_validate_extern_base(PyTypeObject *base); /* proto */
631
+
632
+ /////////////// ValidateExternBase ///////////////
633
+ //@requires: ObjectHandling.c::FormatTypeName
634
+
635
+ static int __Pyx_validate_extern_base(PyTypeObject *base) {
636
+ Py_ssize_t itemsize;
637
+ #if CYTHON_COMPILING_IN_LIMITED_API
638
+ PyObject *py_itemsize;
639
+ #endif
640
+ #if !CYTHON_COMPILING_IN_LIMITED_API
641
+ itemsize = ((PyTypeObject *)base)->tp_itemsize;
642
+ #else
643
+ py_itemsize = PyObject_GetAttrString((PyObject*)base, "__itemsize__");
644
+ if (!py_itemsize)
645
+ return -1;
646
+ itemsize = PyLong_AsSsize_t(py_itemsize);
647
+ Py_DECREF(py_itemsize);
648
+ py_itemsize = 0;
649
+ if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred())
650
+ return -1;
651
+ #endif
652
+ if (itemsize) {
653
+ __Pyx_TypeName b_name = __Pyx_PyType_GetName(base);
654
+ PyErr_Format(PyExc_TypeError,
655
+ "inheritance from PyVarObject types like '" __Pyx_FMT_TYPENAME "' not currently supported", b_name);
656
+ __Pyx_DECREF_TypeName(b_name);
657
+ return -1;
658
+ }
659
+ return 0;
660
+ }
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/FunctionArguments.c ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //////////////////// ArgTypeTest.proto ////////////////////
2
+
3
+
4
+ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact) \
5
+ ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 : \
6
+ __Pyx__ArgTypeTest(obj, type, name, exact))
7
+
8
+ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /*proto*/
9
+
10
+ //////////////////// ArgTypeTest ////////////////////
11
+
12
+ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact)
13
+ {
14
+ __Pyx_TypeName type_name;
15
+ __Pyx_TypeName obj_type_name;
16
+ if (unlikely(!type)) {
17
+ PyErr_SetString(PyExc_SystemError, "Missing type object");
18
+ return 0;
19
+ }
20
+ else if (exact) {
21
+ #if PY_MAJOR_VERSION == 2
22
+ if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
23
+ #endif
24
+ }
25
+ else {
26
+ if (likely(__Pyx_TypeCheck(obj, type))) return 1;
27
+ }
28
+ type_name = __Pyx_PyType_GetName(type);
29
+ obj_type_name = __Pyx_PyType_GetName(Py_TYPE(obj));
30
+ PyErr_Format(PyExc_TypeError,
31
+ "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME
32
+ ", got " __Pyx_FMT_TYPENAME ")", name, type_name, obj_type_name);
33
+ __Pyx_DECREF_TypeName(type_name);
34
+ __Pyx_DECREF_TypeName(obj_type_name);
35
+ return 0;
36
+ }
37
+
38
+ //////////////////// RaiseArgTupleInvalid.proto ////////////////////
39
+
40
+ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
41
+ Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/
42
+
43
+ //////////////////// RaiseArgTupleInvalid ////////////////////
44
+
45
+ // __Pyx_RaiseArgtupleInvalid raises the correct exception when too
46
+ // many or too few positional arguments were found. This handles
47
+ // Py_ssize_t formatting correctly.
48
+
49
+ static void __Pyx_RaiseArgtupleInvalid(
50
+ const char* func_name,
51
+ int exact,
52
+ Py_ssize_t num_min,
53
+ Py_ssize_t num_max,
54
+ Py_ssize_t num_found)
55
+ {
56
+ Py_ssize_t num_expected;
57
+ const char *more_or_less;
58
+
59
+ if (num_found < num_min) {
60
+ num_expected = num_min;
61
+ more_or_less = "at least";
62
+ } else {
63
+ num_expected = num_max;
64
+ more_or_less = "at most";
65
+ }
66
+ if (exact) {
67
+ more_or_less = "exactly";
68
+ }
69
+ PyErr_Format(PyExc_TypeError,
70
+ "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
71
+ func_name, more_or_less, num_expected,
72
+ (num_expected == 1) ? "" : "s", num_found);
73
+ }
74
+
75
+
76
+ //////////////////// RaiseKeywordRequired.proto ////////////////////
77
+
78
+ static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name); /*proto*/
79
+
80
+ //////////////////// RaiseKeywordRequired ////////////////////
81
+
82
+ static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name) {
83
+ PyErr_Format(PyExc_TypeError,
84
+ #if PY_MAJOR_VERSION >= 3
85
+ "%s() needs keyword-only argument %U", func_name, kw_name);
86
+ #else
87
+ "%s() needs keyword-only argument %s", func_name,
88
+ PyString_AS_STRING(kw_name));
89
+ #endif
90
+ }
91
+
92
+
93
+ //////////////////// RaiseDoubleKeywords.proto ////////////////////
94
+
95
+ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/
96
+
97
+ //////////////////// RaiseDoubleKeywords ////////////////////
98
+
99
+ static void __Pyx_RaiseDoubleKeywordsError(
100
+ const char* func_name,
101
+ PyObject* kw_name)
102
+ {
103
+ PyErr_Format(PyExc_TypeError,
104
+ #if PY_MAJOR_VERSION >= 3
105
+ "%s() got multiple values for keyword argument '%U'", func_name, kw_name);
106
+ #else
107
+ "%s() got multiple values for keyword argument '%s'", func_name,
108
+ PyString_AsString(kw_name));
109
+ #endif
110
+ }
111
+
112
+
113
+ //////////////////// RaiseMappingExpected.proto ////////////////////
114
+
115
+ static void __Pyx_RaiseMappingExpectedError(PyObject* arg); /*proto*/
116
+
117
+ //////////////////// RaiseMappingExpected ////////////////////
118
+
119
+ static void __Pyx_RaiseMappingExpectedError(PyObject* arg) {
120
+ __Pyx_TypeName arg_type_name = __Pyx_PyType_GetName(Py_TYPE(arg));
121
+ PyErr_Format(PyExc_TypeError,
122
+ "'" __Pyx_FMT_TYPENAME "' object is not a mapping", arg_type_name);
123
+ __Pyx_DECREF_TypeName(arg_type_name);
124
+ }
125
+
126
+
127
+ //////////////////// KeywordStringCheck.proto ////////////////////
128
+
129
+ static int __Pyx_CheckKeywordStrings(PyObject *kw, const char* function_name, int kw_allowed); /*proto*/
130
+
131
+ //////////////////// KeywordStringCheck ////////////////////
132
+
133
+ // __Pyx_CheckKeywordStrings raises an error if non-string keywords
134
+ // were passed to a function, or if any keywords were passed to a
135
+ // function that does not accept them.
136
+ //
137
+ // The "kw" argument is either a dict (for METH_VARARGS) or a tuple
138
+ // (for METH_FASTCALL).
139
+
140
+ static int __Pyx_CheckKeywordStrings(
141
+ PyObject *kw,
142
+ const char* function_name,
143
+ int kw_allowed)
144
+ {
145
+ PyObject* key = 0;
146
+ Py_ssize_t pos = 0;
147
+ #if CYTHON_COMPILING_IN_PYPY
148
+ /* PyPy appears to check keywords at call time, not at unpacking time => not much to do here */
149
+ if (!kw_allowed && PyDict_Next(kw, &pos, &key, 0))
150
+ goto invalid_keyword;
151
+ return 1;
152
+ #else
153
+ if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kw))) {
154
+ Py_ssize_t kwsize;
155
+ #if CYTHON_ASSUME_SAFE_MACROS
156
+ kwsize = PyTuple_GET_SIZE(kw);
157
+ #else
158
+ kwsize = PyTuple_Size(kw);
159
+ if (kwsize < 0) return 0;
160
+ #endif
161
+ if (unlikely(kwsize == 0))
162
+ return 1;
163
+ if (!kw_allowed) {
164
+ #if CYTHON_ASSUME_SAFE_MACROS
165
+ key = PyTuple_GET_ITEM(kw, 0);
166
+ #else
167
+ key = PyTuple_GetItem(kw, pos);
168
+ if (!key) return 0;
169
+ #endif
170
+ goto invalid_keyword;
171
+ }
172
+ #if PY_VERSION_HEX < 0x03090000
173
+ // On CPython >= 3.9, the FASTCALL protocol guarantees that keyword
174
+ // names are strings (see https://bugs.python.org/issue37540)
175
+ for (pos = 0; pos < kwsize; pos++) {
176
+ #if CYTHON_ASSUME_SAFE_MACROS
177
+ key = PyTuple_GET_ITEM(kw, pos);
178
+ #else
179
+ key = PyTuple_GetItem(kw, pos);
180
+ if (!key) return 0;
181
+ #endif
182
+ if (unlikely(!PyUnicode_Check(key)))
183
+ goto invalid_keyword_type;
184
+ }
185
+ #endif
186
+ return 1;
187
+ }
188
+
189
+ while (PyDict_Next(kw, &pos, &key, 0)) {
190
+ #if PY_MAJOR_VERSION < 3
191
+ if (unlikely(!PyString_Check(key)))
192
+ #endif
193
+ if (unlikely(!PyUnicode_Check(key)))
194
+ goto invalid_keyword_type;
195
+ }
196
+ if (!kw_allowed && unlikely(key))
197
+ goto invalid_keyword;
198
+ return 1;
199
+ invalid_keyword_type:
200
+ PyErr_Format(PyExc_TypeError,
201
+ "%.200s() keywords must be strings", function_name);
202
+ return 0;
203
+ #endif
204
+ invalid_keyword:
205
+ #if PY_MAJOR_VERSION < 3
206
+ PyErr_Format(PyExc_TypeError,
207
+ "%.200s() got an unexpected keyword argument '%.200s'",
208
+ function_name, PyString_AsString(key));
209
+ #else
210
+ PyErr_Format(PyExc_TypeError,
211
+ "%s() got an unexpected keyword argument '%U'",
212
+ function_name, key);
213
+ #endif
214
+ return 0;
215
+ }
216
+
217
+
218
+ //////////////////// ParseKeywords.proto ////////////////////
219
+
220
+ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject *const *kwvalues,
221
+ PyObject **argnames[],
222
+ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,
223
+ const char* function_name); /*proto*/
224
+
225
+ //////////////////// ParseKeywords ////////////////////
226
+ //@requires: RaiseDoubleKeywords
227
+
228
+ // __Pyx_ParseOptionalKeywords copies the optional/unknown keyword
229
+ // arguments from kwds into the dict kwds2. If kwds2 is NULL, unknown
230
+ // keywords will raise an invalid keyword error.
231
+ //
232
+ // When not using METH_FASTCALL, kwds is a dict and kwvalues is NULL.
233
+ // Otherwise, kwds is a tuple with keyword names and kwvalues is a C
234
+ // array with the corresponding values.
235
+ //
236
+ // Three kinds of errors are checked: 1) non-string keywords, 2)
237
+ // unexpected keywords and 3) overlap with positional arguments.
238
+ //
239
+ // If num_posargs is greater 0, it denotes the number of positional
240
+ // arguments that were passed and that must therefore not appear
241
+ // amongst the keywords as well.
242
+ //
243
+ // This method does not check for required keyword arguments.
244
+
245
+ static int __Pyx_ParseOptionalKeywords(
246
+ PyObject *kwds,
247
+ PyObject *const *kwvalues,
248
+ PyObject **argnames[],
249
+ PyObject *kwds2,
250
+ PyObject *values[],
251
+ Py_ssize_t num_pos_args,
252
+ const char* function_name)
253
+ {
254
+ PyObject *key = 0, *value = 0;
255
+ Py_ssize_t pos = 0;
256
+ PyObject*** name;
257
+ PyObject*** first_kw_arg = argnames + num_pos_args;
258
+ int kwds_is_tuple = CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds));
259
+
260
+ while (1) {
261
+ // clean up key and value when the loop is "continued"
262
+ Py_XDECREF(key); key = NULL;
263
+ Py_XDECREF(value); value = NULL;
264
+
265
+ if (kwds_is_tuple) {
266
+ Py_ssize_t size;
267
+ #if CYTHON_ASSUME_SAFE_MACROS
268
+ size = PyTuple_GET_SIZE(kwds);
269
+ #else
270
+ size = PyTuple_Size(kwds);
271
+ if (size < 0) goto bad;
272
+ #endif
273
+ if (pos >= size) break;
274
+
275
+ #if CYTHON_AVOID_BORROWED_REFS
276
+ // Get an owned reference to key.
277
+ key = __Pyx_PySequence_ITEM(kwds, pos);
278
+ if (!key) goto bad;
279
+ #elif CYTHON_ASSUME_SAFE_MACROS
280
+ key = PyTuple_GET_ITEM(kwds, pos);
281
+ #else
282
+ key = PyTuple_GetItem(kwds, pos);
283
+ if (!key) goto bad;
284
+ #endif
285
+
286
+ value = kwvalues[pos];
287
+ pos++;
288
+ }
289
+ else
290
+ {
291
+ if (!PyDict_Next(kwds, &pos, &key, &value)) break;
292
+ // It's unfortunately hard to avoid borrowed references (briefly) with PyDict_Next
293
+ #if CYTHON_AVOID_BORROWED_REFS
294
+ // Own the reference to match the behaviour above.
295
+ Py_INCREF(key);
296
+ #endif
297
+ }
298
+
299
+ name = first_kw_arg;
300
+ while (*name && (**name != key)) name++;
301
+ if (*name) {
302
+ values[name-argnames] = value;
303
+ #if CYTHON_AVOID_BORROWED_REFS
304
+ Py_INCREF(value); /* transfer ownership of value to values */
305
+ Py_DECREF(key);
306
+ #endif
307
+ key = NULL;
308
+ value = NULL;
309
+ continue;
310
+ }
311
+
312
+ // Now make sure we own both references since we're doing non-trivial Python operations.
313
+ #if !CYTHON_AVOID_BORROWED_REFS
314
+ Py_INCREF(key);
315
+ #endif
316
+ Py_INCREF(value);
317
+
318
+ name = first_kw_arg;
319
+ #if PY_MAJOR_VERSION < 3
320
+ if (likely(PyString_Check(key))) {
321
+ while (*name) {
322
+ if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
323
+ && _PyString_Eq(**name, key)) {
324
+ values[name-argnames] = value;
325
+ #if CYTHON_AVOID_BORROWED_REFS
326
+ value = NULL; /* ownership transferred to values */
327
+ #endif
328
+ break;
329
+ }
330
+ name++;
331
+ }
332
+ if (*name) continue;
333
+ else {
334
+ // not found after positional args, check for duplicate
335
+ PyObject*** argname = argnames;
336
+ while (argname != first_kw_arg) {
337
+ if ((**argname == key) || (
338
+ (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
339
+ && _PyString_Eq(**argname, key))) {
340
+ goto arg_passed_twice;
341
+ }
342
+ argname++;
343
+ }
344
+ }
345
+ } else
346
+ #endif
347
+ if (likely(PyUnicode_Check(key))) {
348
+ while (*name) {
349
+ int cmp = (
350
+ #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
351
+ (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
352
+ #endif
353
+ // In Py2, we may need to convert the argument name from str to unicode for comparison.
354
+ PyUnicode_Compare(**name, key)
355
+ );
356
+ if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
357
+ if (cmp == 0) {
358
+ values[name-argnames] = value;
359
+ #if CYTHON_AVOID_BORROWED_REFS
360
+ value = NULL; /* ownership transferred to values */
361
+ #endif
362
+ break;
363
+ }
364
+ name++;
365
+ }
366
+ if (*name) continue;
367
+ else {
368
+ // not found after positional args, check for duplicate
369
+ PyObject*** argname = argnames;
370
+ while (argname != first_kw_arg) {
371
+ int cmp = (**argname == key) ? 0 :
372
+ #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
373
+ (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 :
374
+ #endif
375
+ // need to convert argument name from bytes to unicode for comparison
376
+ PyUnicode_Compare(**argname, key);
377
+ if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
378
+ if (cmp == 0) goto arg_passed_twice;
379
+ argname++;
380
+ }
381
+ }
382
+ } else
383
+ goto invalid_keyword_type;
384
+
385
+ if (kwds2) {
386
+ if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
387
+ } else {
388
+ goto invalid_keyword;
389
+ }
390
+ }
391
+ Py_XDECREF(key);
392
+ Py_XDECREF(value);
393
+ return 0;
394
+ arg_passed_twice:
395
+ __Pyx_RaiseDoubleKeywordsError(function_name, key);
396
+ goto bad;
397
+ invalid_keyword_type:
398
+ PyErr_Format(PyExc_TypeError,
399
+ "%.200s() keywords must be strings", function_name);
400
+ goto bad;
401
+ invalid_keyword:
402
+ #if PY_MAJOR_VERSION < 3
403
+ PyErr_Format(PyExc_TypeError,
404
+ "%.200s() got an unexpected keyword argument '%.200s'",
405
+ function_name, PyString_AsString(key));
406
+ #else
407
+ PyErr_Format(PyExc_TypeError,
408
+ "%s() got an unexpected keyword argument '%U'",
409
+ function_name, key);
410
+ #endif
411
+ bad:
412
+ Py_XDECREF(key);
413
+ Py_XDECREF(value);
414
+ return -1;
415
+ }
416
+
417
+
418
+ //////////////////// MergeKeywords.proto ////////////////////
419
+
420
+ static int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping); /*proto*/
421
+
422
+ //////////////////// MergeKeywords ////////////////////
423
+ //@requires: RaiseDoubleKeywords
424
+ //@requires: Optimize.c::dict_iter
425
+
426
+ static int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping) {
427
+ PyObject *iter, *key = NULL, *value = NULL;
428
+ int source_is_dict, result;
429
+ Py_ssize_t orig_length, ppos = 0;
430
+
431
+ iter = __Pyx_dict_iterator(source_mapping, 0, PYIDENT("items"), &orig_length, &source_is_dict);
432
+ if (unlikely(!iter)) {
433
+ // slow fallback: try converting to dict, then iterate
434
+ PyObject *args;
435
+ if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) goto bad;
436
+ PyErr_Clear();
437
+ args = PyTuple_Pack(1, source_mapping);
438
+ if (likely(args)) {
439
+ PyObject *fallback = PyObject_Call((PyObject*)&PyDict_Type, args, NULL);
440
+ Py_DECREF(args);
441
+ if (likely(fallback)) {
442
+ iter = __Pyx_dict_iterator(fallback, 1, PYIDENT("items"), &orig_length, &source_is_dict);
443
+ Py_DECREF(fallback);
444
+ }
445
+ }
446
+ if (unlikely(!iter)) goto bad;
447
+ }
448
+
449
+ while (1) {
450
+ result = __Pyx_dict_iter_next(iter, orig_length, &ppos, &key, &value, NULL, source_is_dict);
451
+ if (unlikely(result < 0)) goto bad;
452
+ if (!result) break;
453
+
454
+ if (unlikely(PyDict_Contains(kwdict, key))) {
455
+ __Pyx_RaiseDoubleKeywordsError("function", key);
456
+ result = -1;
457
+ } else {
458
+ result = PyDict_SetItem(kwdict, key, value);
459
+ }
460
+ Py_DECREF(key);
461
+ Py_DECREF(value);
462
+ if (unlikely(result < 0)) goto bad;
463
+ }
464
+ Py_XDECREF(iter);
465
+ return 0;
466
+
467
+ bad:
468
+ Py_XDECREF(iter);
469
+ return -1;
470
+ }
471
+
472
+
473
+ /////////////// fastcall.proto ///////////////
474
+
475
+ // We define various functions and macros with two variants:
476
+ //..._FASTCALL and ..._VARARGS
477
+
478
+ // The first is used when METH_FASTCALL is enabled and the second is used
479
+ // otherwise. If the Python implementation does not support METH_FASTCALL
480
+ // (because it's an old version of CPython or it's not CPython at all),
481
+ // then the ..._FASTCALL macros simply alias ..._VARARGS
482
+
483
+ #if CYTHON_AVOID_BORROWED_REFS
484
+ // This is the only case where we request an owned reference.
485
+ #define __Pyx_Arg_VARARGS(args, i) PySequence_GetItem(args, i)
486
+ #elif CYTHON_ASSUME_SAFE_MACROS
487
+ #define __Pyx_Arg_VARARGS(args, i) PyTuple_GET_ITEM(args, i)
488
+ #else
489
+ #define __Pyx_Arg_VARARGS(args, i) PyTuple_GetItem(args, i)
490
+ #endif
491
+ #if CYTHON_AVOID_BORROWED_REFS
492
+ #define __Pyx_Arg_NewRef_VARARGS(arg) __Pyx_NewRef(arg)
493
+ #define __Pyx_Arg_XDECREF_VARARGS(arg) Py_XDECREF(arg)
494
+ #else
495
+ #define __Pyx_Arg_NewRef_VARARGS(arg) arg /* no-op */
496
+ #define __Pyx_Arg_XDECREF_VARARGS(arg) /* no-op - arg is borrowed */
497
+ #endif
498
+ #define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds)
499
+ #define __Pyx_KwValues_VARARGS(args, nargs) NULL
500
+ #define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s)
501
+ #define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw)
502
+ #if CYTHON_METH_FASTCALL
503
+ #define __Pyx_Arg_FASTCALL(args, i) args[i]
504
+ #define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds)
505
+ #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs))
506
+ static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s);
507
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000
508
+ CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues);/*proto*/
509
+ #else
510
+ #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw)
511
+ #endif
512
+ #define __Pyx_Arg_NewRef_FASTCALL(arg) arg /* no-op, __Pyx_Arg_FASTCALL is direct and this needs
513
+ to have the same reference counting */
514
+ #define __Pyx_Arg_XDECREF_FASTCALL(arg) /* no-op - arg was returned from array */
515
+ #else
516
+ #define __Pyx_Arg_FASTCALL __Pyx_Arg_VARARGS
517
+ #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS
518
+ #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS
519
+ #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS
520
+ #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS
521
+ #define __Pyx_Arg_NewRef_FASTCALL(arg) __Pyx_Arg_NewRef_VARARGS(arg)
522
+ #define __Pyx_Arg_XDECREF_FASTCALL(arg) __Pyx_Arg_XDECREF_VARARGS(arg)
523
+ #endif
524
+
525
+ #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
526
+ #define __Pyx_ArgsSlice_VARARGS(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_VARARGS(args, start), stop - start)
527
+ #define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_FASTCALL(args, start), stop - start)
528
+ #else
529
+ /* Not CPython, so certainly no METH_FASTCALL support */
530
+ #define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop)
531
+ #define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop)
532
+ #endif
533
+
534
+
535
+ /////////////// fastcall ///////////////
536
+ //@requires: ObjectHandling.c::TupleAndListFromArray
537
+ //@requires: StringTools.c::UnicodeEquals
538
+
539
+ #if CYTHON_METH_FASTCALL
540
+ // kwnames: tuple with names of keyword arguments
541
+ // kwvalues: C array with values of keyword arguments
542
+ // s: str with the keyword name to look for
543
+ static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s)
544
+ {
545
+ // Search the kwnames array for s and return the corresponding value.
546
+ // We do two loops: a first one to compare pointers (which will find a
547
+ // match if the name in kwnames is interned, given that s is interned
548
+ // by Cython). A second loop compares the actual strings.
549
+ Py_ssize_t i, n = PyTuple_GET_SIZE(kwnames);
550
+ for (i = 0; i < n; i++)
551
+ {
552
+ if (s == PyTuple_GET_ITEM(kwnames, i)) return kwvalues[i];
553
+ }
554
+ for (i = 0; i < n; i++)
555
+ {
556
+ int eq = __Pyx_PyUnicode_Equals(s, PyTuple_GET_ITEM(kwnames, i), Py_EQ);
557
+ if (unlikely(eq != 0)) {
558
+ if (unlikely(eq < 0)) return NULL; /* error */
559
+ return kwvalues[i];
560
+ }
561
+ }
562
+ return NULL; /* not found (no exception set) */
563
+ }
564
+
565
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000
566
+ CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) {
567
+ Py_ssize_t i, nkwargs = PyTuple_GET_SIZE(kwnames);
568
+ PyObject *dict;
569
+
570
+ dict = PyDict_New();
571
+ if (unlikely(!dict))
572
+ return NULL;
573
+
574
+ for (i=0; i<nkwargs; i++) {
575
+ PyObject *key = PyTuple_GET_ITEM(kwnames, i);
576
+ if (unlikely(PyDict_SetItem(dict, key, kwvalues[i]) < 0))
577
+ goto bad;
578
+ }
579
+ return dict;
580
+
581
+ bad:
582
+ Py_DECREF(dict);
583
+ return NULL;
584
+ }
585
+ #endif
586
+
587
+ #endif
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/MemoryView.pyx ADDED
@@ -0,0 +1,1481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################### View.MemoryView ####################
2
+
3
+ # cython: language_level=3str
4
+ # cython: binding=False
5
+
6
+ # This utility provides cython.array and cython.view.memoryview
7
+
8
+ from __future__ import absolute_import
9
+
10
+ cimport cython
11
+
12
+ # from cpython cimport ...
13
+ cdef extern from "Python.h":
14
+ ctypedef struct PyObject
15
+ int PyIndex_Check(object)
16
+ PyObject *PyExc_IndexError
17
+ PyObject *PyExc_ValueError
18
+
19
+ cdef extern from "pythread.h":
20
+ ctypedef void *PyThread_type_lock
21
+
22
+ PyThread_type_lock PyThread_allocate_lock()
23
+ void PyThread_free_lock(PyThread_type_lock)
24
+
25
+ cdef extern from "<string.h>":
26
+ void *memset(void *b, int c, size_t len)
27
+
28
+ cdef extern from *:
29
+ bint __PYX_CYTHON_ATOMICS_ENABLED()
30
+ int __Pyx_GetBuffer(object, Py_buffer *, int) except -1
31
+ void __Pyx_ReleaseBuffer(Py_buffer *)
32
+
33
+ ctypedef struct PyObject
34
+ ctypedef Py_ssize_t Py_intptr_t
35
+ void Py_INCREF(PyObject *)
36
+ void Py_DECREF(PyObject *)
37
+
38
+ void* PyMem_Malloc(size_t n)
39
+ void PyMem_Free(void *p)
40
+ void* PyObject_Malloc(size_t n)
41
+ void PyObject_Free(void *p)
42
+
43
+ cdef struct __pyx_memoryview "__pyx_memoryview_obj":
44
+ Py_buffer view
45
+ PyObject *obj
46
+ __Pyx_TypeInfo *typeinfo
47
+
48
+ ctypedef struct {{memviewslice_name}}:
49
+ __pyx_memoryview *memview
50
+ char *data
51
+ Py_ssize_t shape[{{max_dims}}]
52
+ Py_ssize_t strides[{{max_dims}}]
53
+ Py_ssize_t suboffsets[{{max_dims}}]
54
+
55
+ void __PYX_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil)
56
+ void __PYX_XCLEAR_MEMVIEW({{memviewslice_name}} *memslice, int have_gil)
57
+
58
+ ctypedef struct __pyx_buffer "Py_buffer":
59
+ PyObject *obj
60
+
61
+ PyObject *Py_None
62
+
63
+ cdef enum:
64
+ PyBUF_C_CONTIGUOUS,
65
+ PyBUF_F_CONTIGUOUS,
66
+ PyBUF_ANY_CONTIGUOUS
67
+ PyBUF_FORMAT
68
+ PyBUF_WRITABLE
69
+ PyBUF_STRIDES
70
+ PyBUF_INDIRECT
71
+ PyBUF_ND
72
+ PyBUF_RECORDS
73
+ PyBUF_RECORDS_RO
74
+
75
+ ctypedef struct __Pyx_TypeInfo:
76
+ pass
77
+
78
+ cdef extern from *:
79
+ ctypedef int __pyx_atomic_int_type
80
+ {{memviewslice_name}} slice_copy_contig "__pyx_memoryview_copy_new_contig"(
81
+ __Pyx_memviewslice *from_mvs,
82
+ char *mode, int ndim,
83
+ size_t sizeof_dtype, int contig_flag,
84
+ bint dtype_is_object) except * nogil
85
+ bint slice_is_contig "__pyx_memviewslice_is_contig" (
86
+ {{memviewslice_name}} mvs, char order, int ndim) nogil
87
+ bint slices_overlap "__pyx_slices_overlap" ({{memviewslice_name}} *slice1,
88
+ {{memviewslice_name}} *slice2,
89
+ int ndim, size_t itemsize) nogil
90
+
91
+
92
+ cdef extern from "<stdlib.h>":
93
+ void *malloc(size_t) nogil
94
+ void free(void *) nogil
95
+ void *memcpy(void *dest, void *src, size_t n) nogil
96
+
97
+ # the sequence abstract base class
98
+ cdef object __pyx_collections_abc_Sequence "__pyx_collections_abc_Sequence"
99
+ try:
100
+ if __import__("sys").version_info >= (3, 3):
101
+ __pyx_collections_abc_Sequence = __import__("collections.abc").abc.Sequence
102
+ else:
103
+ __pyx_collections_abc_Sequence = __import__("collections").Sequence
104
+ except:
105
+ # it isn't a big problem if this fails
106
+ __pyx_collections_abc_Sequence = None
107
+
108
+ #
109
+ ### cython.array class
110
+ #
111
+
112
+ @cython.collection_type("sequence")
113
+ @cname("__pyx_array")
114
+ cdef class array:
115
+
116
+ cdef:
117
+ char *data
118
+ Py_ssize_t len
119
+ char *format
120
+ int ndim
121
+ Py_ssize_t *_shape
122
+ Py_ssize_t *_strides
123
+ Py_ssize_t itemsize
124
+ unicode mode # FIXME: this should have been a simple 'char'
125
+ bytes _format
126
+ void (*callback_free_data)(void *data) noexcept
127
+ # cdef object _memview
128
+ cdef bint free_data
129
+ cdef bint dtype_is_object
130
+
131
+ def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None,
132
+ mode="c", bint allocate_buffer=True):
133
+
134
+ cdef int idx
135
+ cdef Py_ssize_t dim
136
+
137
+ self.ndim = <int> len(shape)
138
+ self.itemsize = itemsize
139
+
140
+ if not self.ndim:
141
+ raise ValueError, "Empty shape tuple for cython.array"
142
+
143
+ if itemsize <= 0:
144
+ raise ValueError, "itemsize <= 0 for cython.array"
145
+
146
+ if not isinstance(format, bytes):
147
+ format = format.encode('ASCII')
148
+ self._format = format # keep a reference to the byte string
149
+ self.format = self._format
150
+
151
+ # use single malloc() for both shape and strides
152
+ self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2)
153
+ self._strides = self._shape + self.ndim
154
+
155
+ if not self._shape:
156
+ raise MemoryError, "unable to allocate shape and strides."
157
+
158
+ # cdef Py_ssize_t dim, stride
159
+ for idx, dim in enumerate(shape):
160
+ if dim <= 0:
161
+ raise ValueError, f"Invalid shape in axis {idx}: {dim}."
162
+ self._shape[idx] = dim
163
+
164
+ cdef char order
165
+ if mode == 'c':
166
+ order = b'C'
167
+ self.mode = u'c'
168
+ elif mode == 'fortran':
169
+ order = b'F'
170
+ self.mode = u'fortran'
171
+ else:
172
+ raise ValueError, f"Invalid mode, expected 'c' or 'fortran', got {mode}"
173
+
174
+ self.len = fill_contig_strides_array(self._shape, self._strides, itemsize, self.ndim, order)
175
+
176
+ self.free_data = allocate_buffer
177
+ self.dtype_is_object = format == b'O'
178
+
179
+ if allocate_buffer:
180
+ _allocate_buffer(self)
181
+
182
+ @cname('getbuffer')
183
+ def __getbuffer__(self, Py_buffer *info, int flags):
184
+ cdef int bufmode = -1
185
+ if flags & (PyBUF_C_CONTIGUOUS | PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS):
186
+ if self.mode == u"c":
187
+ bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
188
+ elif self.mode == u"fortran":
189
+ bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
190
+ if not (flags & bufmode):
191
+ raise ValueError, "Can only create a buffer that is contiguous in memory."
192
+ info.buf = self.data
193
+ info.len = self.len
194
+
195
+ if flags & PyBUF_STRIDES:
196
+ info.ndim = self.ndim
197
+ info.shape = self._shape
198
+ info.strides = self._strides
199
+ else:
200
+ info.ndim = 1
201
+ info.shape = &self.len if flags & PyBUF_ND else NULL
202
+ info.strides = NULL
203
+
204
+ info.suboffsets = NULL
205
+ info.itemsize = self.itemsize
206
+ info.readonly = 0
207
+ info.format = self.format if flags & PyBUF_FORMAT else NULL
208
+ info.obj = self
209
+
210
+ def __dealloc__(array self):
211
+ if self.callback_free_data != NULL:
212
+ self.callback_free_data(self.data)
213
+ elif self.free_data and self.data is not NULL:
214
+ if self.dtype_is_object:
215
+ refcount_objects_in_slice(self.data, self._shape, self._strides, self.ndim, inc=False)
216
+ free(self.data)
217
+ PyObject_Free(self._shape)
218
+
219
+ @property
220
+ def memview(self):
221
+ return self.get_memview()
222
+
223
+ @cname('get_memview')
224
+ cdef get_memview(self):
225
+ flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE
226
+ return memoryview(self, flags, self.dtype_is_object)
227
+
228
+ def __len__(self):
229
+ return self._shape[0]
230
+
231
+ def __getattr__(self, attr):
232
+ return getattr(self.memview, attr)
233
+
234
+ def __getitem__(self, item):
235
+ return self.memview[item]
236
+
237
+ def __setitem__(self, item, value):
238
+ self.memview[item] = value
239
+
240
+ # Sequence methods
241
+ try:
242
+ count = __pyx_collections_abc_Sequence.count
243
+ index = __pyx_collections_abc_Sequence.index
244
+ except:
245
+ pass
246
+
247
+ @cname("__pyx_array_allocate_buffer")
248
+ cdef int _allocate_buffer(array self) except -1:
249
+ # use malloc() for backwards compatibility
250
+ # in case external code wants to change the data pointer
251
+ cdef Py_ssize_t i
252
+ cdef PyObject **p
253
+
254
+ self.free_data = True
255
+ self.data = <char *>malloc(self.len)
256
+ if not self.data:
257
+ raise MemoryError, "unable to allocate array data."
258
+
259
+ if self.dtype_is_object:
260
+ p = <PyObject **> self.data
261
+ for i in range(self.len // self.itemsize):
262
+ p[i] = Py_None
263
+ Py_INCREF(Py_None)
264
+ return 0
265
+
266
+
267
+ @cname("__pyx_array_new")
268
+ cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, char *c_mode, char *buf):
269
+ cdef array result
270
+ cdef str mode = "fortran" if c_mode[0] == b'f' else "c" # this often comes from a constant C string.
271
+
272
+ if buf is NULL:
273
+ result = array.__new__(array, shape, itemsize, format, mode)
274
+ else:
275
+ result = array.__new__(array, shape, itemsize, format, mode, allocate_buffer=False)
276
+ result.data = buf
277
+
278
+ return result
279
+
280
+
281
+ #
282
+ ### Memoryview constants and cython.view.memoryview class
283
+ #
284
+
285
+ # Disable generic_contiguous, as it makes trouble verifying contiguity:
286
+ # - 'contiguous' or '::1' means the dimension is contiguous with dtype
287
+ # - 'indirect_contiguous' means a contiguous list of pointers
288
+ # - dtype contiguous must be contiguous in the first or last dimension
289
+ # from the start, or from the dimension following the last indirect dimension
290
+ #
291
+ # e.g.
292
+ # int[::indirect_contiguous, ::contiguous, :]
293
+ #
294
+ # is valid (list of pointers to 2d fortran-contiguous array), but
295
+ #
296
+ # int[::generic_contiguous, ::contiguous, :]
297
+ #
298
+ # would mean you'd have assert dimension 0 to be indirect (and pointer contiguous) at runtime.
299
+ # So it doesn't bring any performance benefit, and it's only confusing.
300
+
301
+ @cname('__pyx_MemviewEnum')
302
+ cdef class Enum(object):
303
+ cdef object name
304
+ def __init__(self, name):
305
+ self.name = name
306
+ def __repr__(self):
307
+ return self.name
308
+
309
+ cdef generic = Enum("<strided and direct or indirect>")
310
+ cdef strided = Enum("<strided and direct>") # default
311
+ cdef indirect = Enum("<strided and indirect>")
312
+ # Disable generic_contiguous, as it is a troublemaker
313
+ #cdef generic_contiguous = Enum("<contiguous and direct or indirect>")
314
+ cdef contiguous = Enum("<contiguous and direct>")
315
+ cdef indirect_contiguous = Enum("<contiguous and indirect>")
316
+
317
+ # 'follow' is implied when the first or last axis is ::1
318
+
319
+
320
+ # pre-allocate thread locks for reuse
321
+ ## note that this could be implemented in a more beautiful way in "normal" Cython,
322
+ ## but this code gets merged into the user module and not everything works there.
323
+ cdef int __pyx_memoryview_thread_locks_used = 0
324
+ cdef PyThread_type_lock[{{THREAD_LOCKS_PREALLOCATED}}] __pyx_memoryview_thread_locks = [
325
+ {{for _ in range(THREAD_LOCKS_PREALLOCATED)}}
326
+ PyThread_allocate_lock(),
327
+ {{endfor}}
328
+ ]
329
+
330
+
331
+ @cname('__pyx_memoryview')
332
+ cdef class memoryview:
333
+
334
+ cdef object obj
335
+ cdef object _size
336
+ cdef object _array_interface
337
+ cdef PyThread_type_lock lock
338
+ cdef __pyx_atomic_int_type acquisition_count
339
+ cdef Py_buffer view
340
+ cdef int flags
341
+ cdef bint dtype_is_object
342
+ cdef __Pyx_TypeInfo *typeinfo
343
+
344
+ def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False):
345
+ self.obj = obj
346
+ self.flags = flags
347
+ if type(self) is memoryview or obj is not None:
348
+ __Pyx_GetBuffer(obj, &self.view, flags)
349
+ if <PyObject *> self.view.obj == NULL:
350
+ (<__pyx_buffer *> &self.view).obj = Py_None
351
+ Py_INCREF(Py_None)
352
+
353
+ if not __PYX_CYTHON_ATOMICS_ENABLED():
354
+ global __pyx_memoryview_thread_locks_used
355
+ if __pyx_memoryview_thread_locks_used < {{THREAD_LOCKS_PREALLOCATED}}:
356
+ self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]
357
+ __pyx_memoryview_thread_locks_used += 1
358
+ if self.lock is NULL:
359
+ self.lock = PyThread_allocate_lock()
360
+ if self.lock is NULL:
361
+ raise MemoryError
362
+
363
+ if flags & PyBUF_FORMAT:
364
+ self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0')
365
+ else:
366
+ self.dtype_is_object = dtype_is_object
367
+
368
+ assert <Py_intptr_t><void*>(&self.acquisition_count) % sizeof(__pyx_atomic_int_type) == 0
369
+ self.typeinfo = NULL
370
+
371
+ def __dealloc__(memoryview self):
372
+ if self.obj is not None:
373
+ __Pyx_ReleaseBuffer(&self.view)
374
+ elif (<__pyx_buffer *> &self.view).obj == Py_None:
375
+ # Undo the incref in __cinit__() above.
376
+ (<__pyx_buffer *> &self.view).obj = NULL
377
+ Py_DECREF(Py_None)
378
+
379
+ cdef int i
380
+ global __pyx_memoryview_thread_locks_used
381
+ if self.lock != NULL:
382
+ for i in range(__pyx_memoryview_thread_locks_used):
383
+ if __pyx_memoryview_thread_locks[i] is self.lock:
384
+ __pyx_memoryview_thread_locks_used -= 1
385
+ if i != __pyx_memoryview_thread_locks_used:
386
+ __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = (
387
+ __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i])
388
+ break
389
+ else:
390
+ PyThread_free_lock(self.lock)
391
+
392
+ cdef char *get_item_pointer(memoryview self, object index) except NULL:
393
+ cdef Py_ssize_t dim
394
+ cdef char *itemp = <char *> self.view.buf
395
+
396
+ for dim, idx in enumerate(index):
397
+ itemp = pybuffer_index(&self.view, itemp, idx, dim)
398
+
399
+ return itemp
400
+
401
+ #@cname('__pyx_memoryview_getitem')
402
+ def __getitem__(memoryview self, object index):
403
+ if index is Ellipsis:
404
+ return self
405
+
406
+ have_slices, indices = _unellipsify(index, self.view.ndim)
407
+
408
+ cdef char *itemp
409
+ if have_slices:
410
+ return memview_slice(self, indices)
411
+ else:
412
+ itemp = self.get_item_pointer(indices)
413
+ return self.convert_item_to_object(itemp)
414
+
415
+ def __setitem__(memoryview self, object index, object value):
416
+ if self.view.readonly:
417
+ raise TypeError, "Cannot assign to read-only memoryview"
418
+
419
+ have_slices, index = _unellipsify(index, self.view.ndim)
420
+
421
+ if have_slices:
422
+ obj = self.is_slice(value)
423
+ if obj is not None:
424
+ self.setitem_slice_assignment(self[index], obj)
425
+ else:
426
+ self.setitem_slice_assign_scalar(self[index], value)
427
+ else:
428
+ self.setitem_indexed(index, value)
429
+
430
+ cdef is_slice(self, obj):
431
+ if not isinstance(obj, memoryview):
432
+ try:
433
+ obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS,
434
+ self.dtype_is_object)
435
+ except TypeError:
436
+ return None
437
+
438
+ return obj
439
+
440
+ cdef setitem_slice_assignment(self, dst, src):
441
+ cdef {{memviewslice_name}} dst_slice
442
+ cdef {{memviewslice_name}} src_slice
443
+ cdef {{memviewslice_name}} msrc = get_slice_from_memview(src, &src_slice)[0]
444
+ cdef {{memviewslice_name}} mdst = get_slice_from_memview(dst, &dst_slice)[0]
445
+
446
+ memoryview_copy_contents(msrc, mdst, src.ndim, dst.ndim, self.dtype_is_object)
447
+
448
+ cdef setitem_slice_assign_scalar(self, memoryview dst, value):
449
+ cdef int array[128]
450
+ cdef void *tmp = NULL
451
+ cdef void *item
452
+
453
+ cdef {{memviewslice_name}} *dst_slice
454
+ cdef {{memviewslice_name}} tmp_slice
455
+ dst_slice = get_slice_from_memview(dst, &tmp_slice)
456
+
457
+ if <size_t>self.view.itemsize > sizeof(array):
458
+ tmp = PyMem_Malloc(self.view.itemsize)
459
+ if tmp == NULL:
460
+ raise MemoryError
461
+ item = tmp
462
+ else:
463
+ item = <void *> array
464
+
465
+ try:
466
+ if self.dtype_is_object:
467
+ (<PyObject **> item)[0] = <PyObject *> value
468
+ else:
469
+ self.assign_item_from_object(<char *> item, value)
470
+
471
+ # It would be easy to support indirect dimensions, but it's easier
472
+ # to disallow :)
473
+ if self.view.suboffsets != NULL:
474
+ assert_direct_dimensions(self.view.suboffsets, self.view.ndim)
475
+ slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize,
476
+ item, self.dtype_is_object)
477
+ finally:
478
+ PyMem_Free(tmp)
479
+
480
+ cdef setitem_indexed(self, index, value):
481
+ cdef char *itemp = self.get_item_pointer(index)
482
+ self.assign_item_from_object(itemp, value)
483
+
484
+ cdef convert_item_to_object(self, char *itemp):
485
+ """Only used if instantiated manually by the user, or if Cython doesn't
486
+ know how to convert the type"""
487
+ import struct
488
+ cdef bytes bytesitem
489
+ # Do a manual and complete check here instead of this easy hack
490
+ bytesitem = itemp[:self.view.itemsize]
491
+ try:
492
+ result = struct.unpack(self.view.format, bytesitem)
493
+ except struct.error:
494
+ raise ValueError, "Unable to convert item to object"
495
+ else:
496
+ if len(self.view.format) == 1:
497
+ return result[0]
498
+ return result
499
+
500
+ cdef assign_item_from_object(self, char *itemp, object value):
501
+ """Only used if instantiated manually by the user, or if Cython doesn't
502
+ know how to convert the type"""
503
+ import struct
504
+ cdef char c
505
+ cdef bytes bytesvalue
506
+ cdef Py_ssize_t i
507
+
508
+ if isinstance(value, tuple):
509
+ bytesvalue = struct.pack(self.view.format, *value)
510
+ else:
511
+ bytesvalue = struct.pack(self.view.format, value)
512
+
513
+ for i, c in enumerate(bytesvalue):
514
+ itemp[i] = c
515
+
516
+ @cname('getbuffer')
517
+ def __getbuffer__(self, Py_buffer *info, int flags):
518
+ if flags & PyBUF_WRITABLE and self.view.readonly:
519
+ raise ValueError, "Cannot create writable memory view from read-only memoryview"
520
+
521
+ if flags & PyBUF_ND:
522
+ info.shape = self.view.shape
523
+ else:
524
+ info.shape = NULL
525
+
526
+ if flags & PyBUF_STRIDES:
527
+ info.strides = self.view.strides
528
+ else:
529
+ info.strides = NULL
530
+
531
+ if flags & PyBUF_INDIRECT:
532
+ info.suboffsets = self.view.suboffsets
533
+ else:
534
+ info.suboffsets = NULL
535
+
536
+ if flags & PyBUF_FORMAT:
537
+ info.format = self.view.format
538
+ else:
539
+ info.format = NULL
540
+
541
+ info.buf = self.view.buf
542
+ info.ndim = self.view.ndim
543
+ info.itemsize = self.view.itemsize
544
+ info.len = self.view.len
545
+ info.readonly = self.view.readonly
546
+ info.obj = self
547
+
548
+ # Some properties that have the same semantics as in NumPy
549
+ @property
550
+ def T(self):
551
+ cdef _memoryviewslice result = memoryview_copy(self)
552
+ transpose_memslice(&result.from_slice)
553
+ return result
554
+
555
+ @property
556
+ def base(self):
557
+ return self._get_base()
558
+
559
+ cdef _get_base(self):
560
+ return self.obj
561
+
562
+ @property
563
+ def shape(self):
564
+ return tuple([length for length in self.view.shape[:self.view.ndim]])
565
+
566
+ @property
567
+ def strides(self):
568
+ if self.view.strides == NULL:
569
+ # Note: we always ask for strides, so if this is not set it's a bug
570
+ raise ValueError, "Buffer view does not expose strides"
571
+
572
+ return tuple([stride for stride in self.view.strides[:self.view.ndim]])
573
+
574
+ @property
575
+ def suboffsets(self):
576
+ if self.view.suboffsets == NULL:
577
+ return (-1,) * self.view.ndim
578
+
579
+ return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]])
580
+
581
+ @property
582
+ def ndim(self):
583
+ return self.view.ndim
584
+
585
+ @property
586
+ def itemsize(self):
587
+ return self.view.itemsize
588
+
589
+ @property
590
+ def nbytes(self):
591
+ return self.size * self.view.itemsize
592
+
593
+ @property
594
+ def size(self):
595
+ if self._size is None:
596
+ result = 1
597
+
598
+ for length in self.view.shape[:self.view.ndim]:
599
+ result *= length
600
+
601
+ self._size = result
602
+
603
+ return self._size
604
+
605
+ def __len__(self):
606
+ if self.view.ndim >= 1:
607
+ return self.view.shape[0]
608
+
609
+ return 0
610
+
611
+ def __repr__(self):
612
+ return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__,
613
+ id(self))
614
+
615
+ def __str__(self):
616
+ return "<MemoryView of %r object>" % (self.base.__class__.__name__,)
617
+
618
+ # Support the same attributes as memoryview slices
619
+ def is_c_contig(self):
620
+ cdef {{memviewslice_name}} *mslice
621
+ cdef {{memviewslice_name}} tmp
622
+ mslice = get_slice_from_memview(self, &tmp)
623
+ return slice_is_contig(mslice[0], 'C', self.view.ndim)
624
+
625
+ def is_f_contig(self):
626
+ cdef {{memviewslice_name}} *mslice
627
+ cdef {{memviewslice_name}} tmp
628
+ mslice = get_slice_from_memview(self, &tmp)
629
+ return slice_is_contig(mslice[0], 'F', self.view.ndim)
630
+
631
+ def copy(self):
632
+ cdef {{memviewslice_name}} mslice
633
+ cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS
634
+
635
+ slice_copy(self, &mslice)
636
+ mslice = slice_copy_contig(&mslice, "c", self.view.ndim,
637
+ self.view.itemsize,
638
+ flags|PyBUF_C_CONTIGUOUS,
639
+ self.dtype_is_object)
640
+
641
+ return memoryview_copy_from_slice(self, &mslice)
642
+
643
+ def copy_fortran(self):
644
+ cdef {{memviewslice_name}} src, dst
645
+ cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS
646
+
647
+ slice_copy(self, &src)
648
+ dst = slice_copy_contig(&src, "fortran", self.view.ndim,
649
+ self.view.itemsize,
650
+ flags|PyBUF_F_CONTIGUOUS,
651
+ self.dtype_is_object)
652
+
653
+ return memoryview_copy_from_slice(self, &dst)
654
+
655
+
656
+ @cname('__pyx_memoryview_new')
657
+ cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo):
658
+ cdef memoryview result = memoryview(o, flags, dtype_is_object)
659
+ result.typeinfo = typeinfo
660
+ return result
661
+
662
+ @cname('__pyx_memoryview_check')
663
+ cdef inline bint memoryview_check(object o) noexcept:
664
+ return isinstance(o, memoryview)
665
+
666
+ cdef tuple _unellipsify(object index, int ndim):
667
+ """
668
+ Replace all ellipses with full slices and fill incomplete indices with
669
+ full slices.
670
+ """
671
+ cdef Py_ssize_t idx
672
+ tup = <tuple>index if isinstance(index, tuple) else (index,)
673
+
674
+ result = [slice(None)] * ndim
675
+ have_slices = False
676
+ seen_ellipsis = False
677
+ idx = 0
678
+ for item in tup:
679
+ if item is Ellipsis:
680
+ if not seen_ellipsis:
681
+ idx += ndim - len(tup)
682
+ seen_ellipsis = True
683
+ have_slices = True
684
+ else:
685
+ if isinstance(item, slice):
686
+ have_slices = True
687
+ elif not PyIndex_Check(item):
688
+ raise TypeError, f"Cannot index with type '{type(item)}'"
689
+ result[idx] = item
690
+ idx += 1
691
+
692
+ nslices = ndim - idx
693
+ return have_slices or nslices, tuple(result)
694
+
695
+ cdef int assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim) except -1:
696
+ for suboffset in suboffsets[:ndim]:
697
+ if suboffset >= 0:
698
+ raise ValueError, "Indirect dimensions not supported"
699
+ return 0 # return type just used as an error flag
700
+
701
+ #
702
+ ### Slicing a memoryview
703
+ #
704
+
705
+ @cname('__pyx_memview_slice')
706
+ cdef memoryview memview_slice(memoryview memview, object indices):
707
+ cdef int new_ndim = 0, suboffset_dim = -1, dim
708
+ cdef bint negative_step
709
+ cdef {{memviewslice_name}} src, dst
710
+ cdef {{memviewslice_name}} *p_src
711
+
712
+ # dst is copied by value in memoryview_fromslice -- initialize it
713
+ # src is never copied
714
+ memset(&dst, 0, sizeof(dst))
715
+
716
+ cdef _memoryviewslice memviewsliceobj
717
+
718
+ assert memview.view.ndim > 0
719
+
720
+ if isinstance(memview, _memoryviewslice):
721
+ memviewsliceobj = memview
722
+ p_src = &memviewsliceobj.from_slice
723
+ else:
724
+ slice_copy(memview, &src)
725
+ p_src = &src
726
+
727
+ # Note: don't use variable src at this point
728
+ # SubNote: we should be able to declare variables in blocks...
729
+
730
+ # memoryview_fromslice() will inc our dst slice
731
+ dst.memview = p_src.memview
732
+ dst.data = p_src.data
733
+
734
+ # Put everything in temps to avoid this bloody warning:
735
+ # "Argument evaluation order in C function call is undefined and
736
+ # may not be as expected"
737
+ cdef {{memviewslice_name}} *p_dst = &dst
738
+ cdef int *p_suboffset_dim = &suboffset_dim
739
+ cdef Py_ssize_t start, stop, step, cindex
740
+ cdef bint have_start, have_stop, have_step
741
+
742
+ for dim, index in enumerate(indices):
743
+ if PyIndex_Check(index):
744
+ cindex = index
745
+ slice_memviewslice(
746
+ p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
747
+ dim, new_ndim, p_suboffset_dim,
748
+ cindex, 0, 0, # start, stop, step
749
+ 0, 0, 0, # have_{start,stop,step}
750
+ False)
751
+ elif index is None:
752
+ p_dst.shape[new_ndim] = 1
753
+ p_dst.strides[new_ndim] = 0
754
+ p_dst.suboffsets[new_ndim] = -1
755
+ new_ndim += 1
756
+ else:
757
+ start = index.start or 0
758
+ stop = index.stop or 0
759
+ step = index.step or 0
760
+
761
+ have_start = index.start is not None
762
+ have_stop = index.stop is not None
763
+ have_step = index.step is not None
764
+
765
+ slice_memviewslice(
766
+ p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
767
+ dim, new_ndim, p_suboffset_dim,
768
+ start, stop, step,
769
+ have_start, have_stop, have_step,
770
+ True)
771
+ new_ndim += 1
772
+
773
+ if isinstance(memview, _memoryviewslice):
774
+ return memoryview_fromslice(dst, new_ndim,
775
+ memviewsliceobj.to_object_func,
776
+ memviewsliceobj.to_dtype_func,
777
+ memview.dtype_is_object)
778
+ else:
779
+ return memoryview_fromslice(dst, new_ndim, NULL, NULL,
780
+ memview.dtype_is_object)
781
+
782
+
783
+ #
784
+ ### Slicing in a single dimension of a memoryviewslice
785
+ #
786
+
787
+ @cname('__pyx_memoryview_slice_memviewslice')
788
+ cdef int slice_memviewslice(
789
+ {{memviewslice_name}} *dst,
790
+ Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset,
791
+ int dim, int new_ndim, int *suboffset_dim,
792
+ Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step,
793
+ int have_start, int have_stop, int have_step,
794
+ bint is_slice) except -1 nogil:
795
+ """
796
+ Create a new slice dst given slice src.
797
+
798
+ dim - the current src dimension (indexing will make dimensions
799
+ disappear)
800
+ new_dim - the new dst dimension
801
+ suboffset_dim - pointer to a single int initialized to -1 to keep track of
802
+ where slicing offsets should be added
803
+ """
804
+
805
+ cdef Py_ssize_t new_shape
806
+ cdef bint negative_step
807
+
808
+ if not is_slice:
809
+ # index is a normal integer-like index
810
+ if start < 0:
811
+ start += shape
812
+ if not 0 <= start < shape:
813
+ _err_dim(PyExc_IndexError, "Index out of bounds (axis %d)", dim)
814
+ else:
815
+ # index is a slice
816
+ if have_step:
817
+ negative_step = step < 0
818
+ if step == 0:
819
+ _err_dim(PyExc_ValueError, "Step may not be zero (axis %d)", dim)
820
+ else:
821
+ negative_step = False
822
+ step = 1
823
+
824
+ # check our bounds and set defaults
825
+ if have_start:
826
+ if start < 0:
827
+ start += shape
828
+ if start < 0:
829
+ start = 0
830
+ elif start >= shape:
831
+ if negative_step:
832
+ start = shape - 1
833
+ else:
834
+ start = shape
835
+ else:
836
+ if negative_step:
837
+ start = shape - 1
838
+ else:
839
+ start = 0
840
+
841
+ if have_stop:
842
+ if stop < 0:
843
+ stop += shape
844
+ if stop < 0:
845
+ stop = 0
846
+ elif stop > shape:
847
+ stop = shape
848
+ else:
849
+ if negative_step:
850
+ stop = -1
851
+ else:
852
+ stop = shape
853
+
854
+ # len = ceil( (stop - start) / step )
855
+ with cython.cdivision(True):
856
+ new_shape = (stop - start) // step
857
+
858
+ if (stop - start) - step * new_shape:
859
+ new_shape += 1
860
+
861
+ if new_shape < 0:
862
+ new_shape = 0
863
+
864
+ # shape/strides/suboffsets
865
+ dst.strides[new_ndim] = stride * step
866
+ dst.shape[new_ndim] = new_shape
867
+ dst.suboffsets[new_ndim] = suboffset
868
+
869
+ # Add the slicing or indexing offsets to the right suboffset or base data *
870
+ if suboffset_dim[0] < 0:
871
+ dst.data += start * stride
872
+ else:
873
+ dst.suboffsets[suboffset_dim[0]] += start * stride
874
+
875
+ if suboffset >= 0:
876
+ if not is_slice:
877
+ if new_ndim == 0:
878
+ dst.data = (<char **> dst.data)[0] + suboffset
879
+ else:
880
+ _err_dim(PyExc_IndexError, "All dimensions preceding dimension %d "
881
+ "must be indexed and not sliced", dim)
882
+ else:
883
+ suboffset_dim[0] = new_ndim
884
+
885
+ return 0
886
+
887
+ #
888
+ ### Index a memoryview
889
+ #
890
+ @cname('__pyx_pybuffer_index')
891
+ cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index,
892
+ Py_ssize_t dim) except NULL:
893
+ cdef Py_ssize_t shape, stride, suboffset = -1
894
+ cdef Py_ssize_t itemsize = view.itemsize
895
+ cdef char *resultp
896
+
897
+ if view.ndim == 0:
898
+ shape = view.len // itemsize
899
+ stride = itemsize
900
+ else:
901
+ shape = view.shape[dim]
902
+ stride = view.strides[dim]
903
+ if view.suboffsets != NULL:
904
+ suboffset = view.suboffsets[dim]
905
+
906
+ if index < 0:
907
+ index += view.shape[dim]
908
+ if index < 0:
909
+ raise IndexError, f"Out of bounds on buffer access (axis {dim})"
910
+
911
+ if index >= shape:
912
+ raise IndexError, f"Out of bounds on buffer access (axis {dim})"
913
+
914
+ resultp = bufp + index * stride
915
+ if suboffset >= 0:
916
+ resultp = (<char **> resultp)[0] + suboffset
917
+
918
+ return resultp
919
+
920
+ #
921
+ ### Transposing a memoryviewslice
922
+ #
923
+ @cname('__pyx_memslice_transpose')
924
+ cdef int transpose_memslice({{memviewslice_name}} *memslice) except -1 nogil:
925
+ cdef int ndim = memslice.memview.view.ndim
926
+
927
+ cdef Py_ssize_t *shape = memslice.shape
928
+ cdef Py_ssize_t *strides = memslice.strides
929
+
930
+ # reverse strides and shape
931
+ cdef int i, j
932
+ for i in range(ndim // 2):
933
+ j = ndim - 1 - i
934
+ strides[i], strides[j] = strides[j], strides[i]
935
+ shape[i], shape[j] = shape[j], shape[i]
936
+
937
+ if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0:
938
+ _err(PyExc_ValueError, "Cannot transpose memoryview with indirect dimensions")
939
+
940
+ return 0
941
+
942
+ #
943
+ ### Creating new memoryview objects from slices and memoryviews
944
+ #
945
+ @cython.collection_type("sequence")
946
+ @cname('__pyx_memoryviewslice')
947
+ cdef class _memoryviewslice(memoryview):
948
+ "Internal class for passing memoryview slices to Python"
949
+
950
+ # We need this to keep our shape/strides/suboffset pointers valid
951
+ cdef {{memviewslice_name}} from_slice
952
+ # We need this only to print it's class' name
953
+ cdef object from_object
954
+
955
+ cdef object (*to_object_func)(char *)
956
+ cdef int (*to_dtype_func)(char *, object) except 0
957
+
958
+ def __dealloc__(self):
959
+ __PYX_XCLEAR_MEMVIEW(&self.from_slice, 1)
960
+
961
+ cdef convert_item_to_object(self, char *itemp):
962
+ if self.to_object_func != NULL:
963
+ return self.to_object_func(itemp)
964
+ else:
965
+ return memoryview.convert_item_to_object(self, itemp)
966
+
967
+ cdef assign_item_from_object(self, char *itemp, object value):
968
+ if self.to_dtype_func != NULL:
969
+ self.to_dtype_func(itemp, value)
970
+ else:
971
+ memoryview.assign_item_from_object(self, itemp, value)
972
+
973
+ cdef _get_base(self):
974
+ return self.from_object
975
+
976
+ # Sequence methods
977
+ try:
978
+ count = __pyx_collections_abc_Sequence.count
979
+ index = __pyx_collections_abc_Sequence.index
980
+ except:
981
+ pass
982
+
983
+ try:
984
+ if __pyx_collections_abc_Sequence:
985
+ # The main value of registering _memoryviewslice as a
986
+ # Sequence is that it can be used in structural pattern
987
+ # matching in Python 3.10+
988
+ __pyx_collections_abc_Sequence.register(_memoryviewslice)
989
+ __pyx_collections_abc_Sequence.register(array)
990
+ except:
991
+ pass # ignore failure, it's a minor issue
992
+
993
+ @cname('__pyx_memoryview_fromslice')
994
+ cdef memoryview_fromslice({{memviewslice_name}} memviewslice,
995
+ int ndim,
996
+ object (*to_object_func)(char *),
997
+ int (*to_dtype_func)(char *, object) except 0,
998
+ bint dtype_is_object):
999
+
1000
+ cdef _memoryviewslice result
1001
+
1002
+ if <PyObject *> memviewslice.memview == Py_None:
1003
+ return None
1004
+
1005
+ # assert 0 < ndim <= memviewslice.memview.view.ndim, (
1006
+ # ndim, memviewslice.memview.view.ndim)
1007
+
1008
+ result = _memoryviewslice.__new__(_memoryviewslice, None, 0, dtype_is_object)
1009
+
1010
+ result.from_slice = memviewslice
1011
+ __PYX_INC_MEMVIEW(&memviewslice, 1)
1012
+
1013
+ result.from_object = (<memoryview> memviewslice.memview)._get_base()
1014
+ result.typeinfo = memviewslice.memview.typeinfo
1015
+
1016
+ result.view = memviewslice.memview.view
1017
+ result.view.buf = <void *> memviewslice.data
1018
+ result.view.ndim = ndim
1019
+ (<__pyx_buffer *> &result.view).obj = Py_None
1020
+ Py_INCREF(Py_None)
1021
+
1022
+ if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE:
1023
+ result.flags = PyBUF_RECORDS
1024
+ else:
1025
+ result.flags = PyBUF_RECORDS_RO
1026
+
1027
+ result.view.shape = <Py_ssize_t *> result.from_slice.shape
1028
+ result.view.strides = <Py_ssize_t *> result.from_slice.strides
1029
+
1030
+ # only set suboffsets if actually used, otherwise set to NULL to improve compatibility
1031
+ result.view.suboffsets = NULL
1032
+ for suboffset in result.from_slice.suboffsets[:ndim]:
1033
+ if suboffset >= 0:
1034
+ result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets
1035
+ break
1036
+
1037
+ result.view.len = result.view.itemsize
1038
+ for length in result.view.shape[:ndim]:
1039
+ result.view.len *= length
1040
+
1041
+ result.to_object_func = to_object_func
1042
+ result.to_dtype_func = to_dtype_func
1043
+
1044
+ return result
1045
+
1046
+ @cname('__pyx_memoryview_get_slice_from_memoryview')
1047
+ cdef {{memviewslice_name}} *get_slice_from_memview(memoryview memview,
1048
+ {{memviewslice_name}} *mslice) except NULL:
1049
+ cdef _memoryviewslice obj
1050
+ if isinstance(memview, _memoryviewslice):
1051
+ obj = memview
1052
+ return &obj.from_slice
1053
+ else:
1054
+ slice_copy(memview, mslice)
1055
+ return mslice
1056
+
1057
+ @cname('__pyx_memoryview_slice_copy')
1058
+ cdef void slice_copy(memoryview memview, {{memviewslice_name}} *dst) noexcept:
1059
+ cdef int dim
1060
+ cdef (Py_ssize_t*) shape, strides, suboffsets
1061
+
1062
+ shape = memview.view.shape
1063
+ strides = memview.view.strides
1064
+ suboffsets = memview.view.suboffsets
1065
+
1066
+ dst.memview = <__pyx_memoryview *> memview
1067
+ dst.data = <char *> memview.view.buf
1068
+
1069
+ for dim in range(memview.view.ndim):
1070
+ dst.shape[dim] = shape[dim]
1071
+ dst.strides[dim] = strides[dim]
1072
+ dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1
1073
+
1074
+ @cname('__pyx_memoryview_copy_object')
1075
+ cdef memoryview_copy(memoryview memview):
1076
+ "Create a new memoryview object"
1077
+ cdef {{memviewslice_name}} memviewslice
1078
+ slice_copy(memview, &memviewslice)
1079
+ return memoryview_copy_from_slice(memview, &memviewslice)
1080
+
1081
+ @cname('__pyx_memoryview_copy_object_from_slice')
1082
+ cdef memoryview_copy_from_slice(memoryview memview, {{memviewslice_name}} *memviewslice):
1083
+ """
1084
+ Create a new memoryview object from a given memoryview object and slice.
1085
+ """
1086
+ cdef object (*to_object_func)(char *)
1087
+ cdef int (*to_dtype_func)(char *, object) except 0
1088
+
1089
+ if isinstance(memview, _memoryviewslice):
1090
+ to_object_func = (<_memoryviewslice> memview).to_object_func
1091
+ to_dtype_func = (<_memoryviewslice> memview).to_dtype_func
1092
+ else:
1093
+ to_object_func = NULL
1094
+ to_dtype_func = NULL
1095
+
1096
+ return memoryview_fromslice(memviewslice[0], memview.view.ndim,
1097
+ to_object_func, to_dtype_func,
1098
+ memview.dtype_is_object)
1099
+
1100
+
1101
+ #
1102
+ ### Copy the contents of a memoryview slices
1103
+ #
1104
+ cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) noexcept nogil:
1105
+ return -arg if arg < 0 else arg
1106
+
1107
+ @cname('__pyx_get_best_slice_order')
1108
+ cdef char get_best_order({{memviewslice_name}} *mslice, int ndim) noexcept nogil:
1109
+ """
1110
+ Figure out the best memory access order for a given slice.
1111
+ """
1112
+ cdef int i
1113
+ cdef Py_ssize_t c_stride = 0
1114
+ cdef Py_ssize_t f_stride = 0
1115
+
1116
+ for i in range(ndim - 1, -1, -1):
1117
+ if mslice.shape[i] > 1:
1118
+ c_stride = mslice.strides[i]
1119
+ break
1120
+
1121
+ for i in range(ndim):
1122
+ if mslice.shape[i] > 1:
1123
+ f_stride = mslice.strides[i]
1124
+ break
1125
+
1126
+ if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride):
1127
+ return 'C'
1128
+ else:
1129
+ return 'F'
1130
+
1131
+ @cython.cdivision(True)
1132
+ cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides,
1133
+ char *dst_data, Py_ssize_t *dst_strides,
1134
+ Py_ssize_t *src_shape, Py_ssize_t *dst_shape,
1135
+ int ndim, size_t itemsize) noexcept nogil:
1136
+ # Note: src_extent is 1 if we're broadcasting
1137
+ # dst_extent always >= src_extent as we don't do reductions
1138
+ cdef Py_ssize_t i
1139
+ cdef Py_ssize_t src_extent = src_shape[0]
1140
+ cdef Py_ssize_t dst_extent = dst_shape[0]
1141
+ cdef Py_ssize_t src_stride = src_strides[0]
1142
+ cdef Py_ssize_t dst_stride = dst_strides[0]
1143
+
1144
+ if ndim == 1:
1145
+ if (src_stride > 0 and dst_stride > 0 and
1146
+ <size_t> src_stride == itemsize == <size_t> dst_stride):
1147
+ memcpy(dst_data, src_data, itemsize * dst_extent)
1148
+ else:
1149
+ for i in range(dst_extent):
1150
+ memcpy(dst_data, src_data, itemsize)
1151
+ src_data += src_stride
1152
+ dst_data += dst_stride
1153
+ else:
1154
+ for i in range(dst_extent):
1155
+ _copy_strided_to_strided(src_data, src_strides + 1,
1156
+ dst_data, dst_strides + 1,
1157
+ src_shape + 1, dst_shape + 1,
1158
+ ndim - 1, itemsize)
1159
+ src_data += src_stride
1160
+ dst_data += dst_stride
1161
+
1162
+ cdef void copy_strided_to_strided({{memviewslice_name}} *src,
1163
+ {{memviewslice_name}} *dst,
1164
+ int ndim, size_t itemsize) noexcept nogil:
1165
+ _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides,
1166
+ src.shape, dst.shape, ndim, itemsize)
1167
+
1168
+ @cname('__pyx_memoryview_slice_get_size')
1169
+ cdef Py_ssize_t slice_get_size({{memviewslice_name}} *src, int ndim) noexcept nogil:
1170
+ "Return the size of the memory occupied by the slice in number of bytes"
1171
+ cdef Py_ssize_t shape, size = src.memview.view.itemsize
1172
+
1173
+ for shape in src.shape[:ndim]:
1174
+ size *= shape
1175
+
1176
+ return size
1177
+
1178
+ @cname('__pyx_fill_contig_strides_array')
1179
+ cdef Py_ssize_t fill_contig_strides_array(
1180
+ Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride,
1181
+ int ndim, char order) noexcept nogil:
1182
+ """
1183
+ Fill the strides array for a slice with C or F contiguous strides.
1184
+ This is like PyBuffer_FillContiguousStrides, but compatible with py < 2.6
1185
+ """
1186
+ cdef int idx
1187
+
1188
+ if order == 'F':
1189
+ for idx in range(ndim):
1190
+ strides[idx] = stride
1191
+ stride *= shape[idx]
1192
+ else:
1193
+ for idx in range(ndim - 1, -1, -1):
1194
+ strides[idx] = stride
1195
+ stride *= shape[idx]
1196
+
1197
+ return stride
1198
+
1199
+ @cname('__pyx_memoryview_copy_data_to_temp')
1200
+ cdef void *copy_data_to_temp({{memviewslice_name}} *src,
1201
+ {{memviewslice_name}} *tmpslice,
1202
+ char order,
1203
+ int ndim) except NULL nogil:
1204
+ """
1205
+ Copy a direct slice to temporary contiguous memory. The caller should free
1206
+ the result when done.
1207
+ """
1208
+ cdef int i
1209
+ cdef void *result
1210
+
1211
+ cdef size_t itemsize = src.memview.view.itemsize
1212
+ cdef size_t size = slice_get_size(src, ndim)
1213
+
1214
+ result = malloc(size)
1215
+ if not result:
1216
+ _err_no_memory()
1217
+
1218
+ # tmpslice[0] = src
1219
+ tmpslice.data = <char *> result
1220
+ tmpslice.memview = src.memview
1221
+ for i in range(ndim):
1222
+ tmpslice.shape[i] = src.shape[i]
1223
+ tmpslice.suboffsets[i] = -1
1224
+
1225
+ fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, ndim, order)
1226
+
1227
+ # We need to broadcast strides again
1228
+ for i in range(ndim):
1229
+ if tmpslice.shape[i] == 1:
1230
+ tmpslice.strides[i] = 0
1231
+
1232
+ if slice_is_contig(src[0], order, ndim):
1233
+ memcpy(result, src.data, size)
1234
+ else:
1235
+ copy_strided_to_strided(src, tmpslice, ndim, itemsize)
1236
+
1237
+ return result
1238
+
1239
+ # Use 'with gil' functions and avoid 'with gil' blocks, as the code within the blocks
1240
+ # has temporaries that need the GIL to clean up
1241
+ @cname('__pyx_memoryview_err_extents')
1242
+ cdef int _err_extents(int i, Py_ssize_t extent1,
1243
+ Py_ssize_t extent2) except -1 with gil:
1244
+ raise ValueError, f"got differing extents in dimension {i} (got {extent1} and {extent2})"
1245
+
1246
+ @cname('__pyx_memoryview_err_dim')
1247
+ cdef int _err_dim(PyObject *error, str msg, int dim) except -1 with gil:
1248
+ raise <object>error, msg % dim
1249
+
1250
+ @cname('__pyx_memoryview_err')
1251
+ cdef int _err(PyObject *error, str msg) except -1 with gil:
1252
+ raise <object>error, msg
1253
+
1254
+ @cname('__pyx_memoryview_err_no_memory')
1255
+ cdef int _err_no_memory() except -1 with gil:
1256
+ raise MemoryError
1257
+
1258
+
1259
+ @cname('__pyx_memoryview_copy_contents')
1260
+ cdef int memoryview_copy_contents({{memviewslice_name}} src,
1261
+ {{memviewslice_name}} dst,
1262
+ int src_ndim, int dst_ndim,
1263
+ bint dtype_is_object) except -1 nogil:
1264
+ """
1265
+ Copy memory from slice src to slice dst.
1266
+ Check for overlapping memory and verify the shapes.
1267
+ """
1268
+ cdef void *tmpdata = NULL
1269
+ cdef size_t itemsize = src.memview.view.itemsize
1270
+ cdef int i
1271
+ cdef char order = get_best_order(&src, src_ndim)
1272
+ cdef bint broadcasting = False
1273
+ cdef bint direct_copy = False
1274
+ cdef {{memviewslice_name}} tmp
1275
+
1276
+ if src_ndim < dst_ndim:
1277
+ broadcast_leading(&src, src_ndim, dst_ndim)
1278
+ elif dst_ndim < src_ndim:
1279
+ broadcast_leading(&dst, dst_ndim, src_ndim)
1280
+
1281
+ cdef int ndim = max(src_ndim, dst_ndim)
1282
+
1283
+ for i in range(ndim):
1284
+ if src.shape[i] != dst.shape[i]:
1285
+ if src.shape[i] == 1:
1286
+ broadcasting = True
1287
+ src.strides[i] = 0
1288
+ else:
1289
+ _err_extents(i, dst.shape[i], src.shape[i])
1290
+
1291
+ if src.suboffsets[i] >= 0:
1292
+ _err_dim(PyExc_ValueError, "Dimension %d is not direct", i)
1293
+
1294
+ if slices_overlap(&src, &dst, ndim, itemsize):
1295
+ # slices overlap, copy to temp, copy temp to dst
1296
+ if not slice_is_contig(src, order, ndim):
1297
+ order = get_best_order(&dst, ndim)
1298
+
1299
+ tmpdata = copy_data_to_temp(&src, &tmp, order, ndim)
1300
+ src = tmp
1301
+
1302
+ if not broadcasting:
1303
+ # See if both slices have equal contiguity, in that case perform a
1304
+ # direct copy. This only works when we are not broadcasting.
1305
+ if slice_is_contig(src, 'C', ndim):
1306
+ direct_copy = slice_is_contig(dst, 'C', ndim)
1307
+ elif slice_is_contig(src, 'F', ndim):
1308
+ direct_copy = slice_is_contig(dst, 'F', ndim)
1309
+
1310
+ if direct_copy:
1311
+ # Contiguous slices with same order
1312
+ refcount_copying(&dst, dtype_is_object, ndim, inc=False)
1313
+ memcpy(dst.data, src.data, slice_get_size(&src, ndim))
1314
+ refcount_copying(&dst, dtype_is_object, ndim, inc=True)
1315
+ free(tmpdata)
1316
+ return 0
1317
+
1318
+ if order == 'F' == get_best_order(&dst, ndim):
1319
+ # see if both slices have Fortran order, transpose them to match our
1320
+ # C-style indexing order
1321
+ transpose_memslice(&src)
1322
+ transpose_memslice(&dst)
1323
+
1324
+ refcount_copying(&dst, dtype_is_object, ndim, inc=False)
1325
+ copy_strided_to_strided(&src, &dst, ndim, itemsize)
1326
+ refcount_copying(&dst, dtype_is_object, ndim, inc=True)
1327
+
1328
+ free(tmpdata)
1329
+ return 0
1330
+
1331
+ @cname('__pyx_memoryview_broadcast_leading')
1332
+ cdef void broadcast_leading({{memviewslice_name}} *mslice,
1333
+ int ndim,
1334
+ int ndim_other) noexcept nogil:
1335
+ cdef int i
1336
+ cdef int offset = ndim_other - ndim
1337
+
1338
+ for i in range(ndim - 1, -1, -1):
1339
+ mslice.shape[i + offset] = mslice.shape[i]
1340
+ mslice.strides[i + offset] = mslice.strides[i]
1341
+ mslice.suboffsets[i + offset] = mslice.suboffsets[i]
1342
+
1343
+ for i in range(offset):
1344
+ mslice.shape[i] = 1
1345
+ mslice.strides[i] = mslice.strides[0]
1346
+ mslice.suboffsets[i] = -1
1347
+
1348
+ #
1349
+ ### Take care of refcounting the objects in slices. Do this separately from any copying,
1350
+ ### to minimize acquiring the GIL
1351
+ #
1352
+
1353
+ @cname('__pyx_memoryview_refcount_copying')
1354
+ cdef void refcount_copying({{memviewslice_name}} *dst, bint dtype_is_object, int ndim, bint inc) noexcept nogil:
1355
+ # incref or decref the objects in the destination slice if the dtype is object
1356
+ if dtype_is_object:
1357
+ refcount_objects_in_slice_with_gil(dst.data, dst.shape, dst.strides, ndim, inc)
1358
+
1359
+ @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil')
1360
+ cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape,
1361
+ Py_ssize_t *strides, int ndim,
1362
+ bint inc) noexcept with gil:
1363
+ refcount_objects_in_slice(data, shape, strides, ndim, inc)
1364
+
1365
+ @cname('__pyx_memoryview_refcount_objects_in_slice')
1366
+ cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape,
1367
+ Py_ssize_t *strides, int ndim, bint inc) noexcept:
1368
+ cdef Py_ssize_t i
1369
+ cdef Py_ssize_t stride = strides[0]
1370
+
1371
+ for i in range(shape[0]):
1372
+ if ndim == 1:
1373
+ if inc:
1374
+ Py_INCREF((<PyObject **> data)[0])
1375
+ else:
1376
+ Py_DECREF((<PyObject **> data)[0])
1377
+ else:
1378
+ refcount_objects_in_slice(data, shape + 1, strides + 1, ndim - 1, inc)
1379
+
1380
+ data += stride
1381
+
1382
+ #
1383
+ ### Scalar to slice assignment
1384
+ #
1385
+ @cname('__pyx_memoryview_slice_assign_scalar')
1386
+ cdef void slice_assign_scalar({{memviewslice_name}} *dst, int ndim,
1387
+ size_t itemsize, void *item,
1388
+ bint dtype_is_object) noexcept nogil:
1389
+ refcount_copying(dst, dtype_is_object, ndim, inc=False)
1390
+ _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, itemsize, item)
1391
+ refcount_copying(dst, dtype_is_object, ndim, inc=True)
1392
+
1393
+
1394
+ @cname('__pyx_memoryview__slice_assign_scalar')
1395
+ cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape,
1396
+ Py_ssize_t *strides, int ndim,
1397
+ size_t itemsize, void *item) noexcept nogil:
1398
+ cdef Py_ssize_t i
1399
+ cdef Py_ssize_t stride = strides[0]
1400
+ cdef Py_ssize_t extent = shape[0]
1401
+
1402
+ if ndim == 1:
1403
+ for i in range(extent):
1404
+ memcpy(data, item, itemsize)
1405
+ data += stride
1406
+ else:
1407
+ for i in range(extent):
1408
+ _slice_assign_scalar(data, shape + 1, strides + 1, ndim - 1, itemsize, item)
1409
+ data += stride
1410
+
1411
+
1412
+ ############### BufferFormatFromTypeInfo ###############
1413
+ cdef extern from *:
1414
+ ctypedef struct __Pyx_StructField
1415
+
1416
+ cdef enum:
1417
+ __PYX_BUF_FLAGS_PACKED_STRUCT
1418
+ __PYX_BUF_FLAGS_INTEGER_COMPLEX
1419
+
1420
+ ctypedef struct __Pyx_TypeInfo:
1421
+ char* name
1422
+ __Pyx_StructField* fields
1423
+ size_t size
1424
+ size_t arraysize[8]
1425
+ int ndim
1426
+ char typegroup
1427
+ char is_unsigned
1428
+ int flags
1429
+
1430
+ ctypedef struct __Pyx_StructField:
1431
+ __Pyx_TypeInfo* type
1432
+ char* name
1433
+ size_t offset
1434
+
1435
+ ctypedef struct __Pyx_BufFmt_StackElem:
1436
+ __Pyx_StructField* field
1437
+ size_t parent_offset
1438
+
1439
+ #ctypedef struct __Pyx_BufFmt_Context:
1440
+ # __Pyx_StructField root
1441
+ __Pyx_BufFmt_StackElem* head
1442
+
1443
+ struct __pyx_typeinfo_string:
1444
+ char string[3]
1445
+
1446
+ __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *)
1447
+
1448
+
1449
+ @cname('__pyx_format_from_typeinfo')
1450
+ cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type):
1451
+ cdef __Pyx_StructField *field
1452
+ cdef __pyx_typeinfo_string fmt
1453
+ cdef bytes part, result
1454
+ cdef Py_ssize_t i
1455
+
1456
+ if type.typegroup == 'S':
1457
+ assert type.fields != NULL
1458
+ assert type.fields.type != NULL
1459
+
1460
+ if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT:
1461
+ alignment = b'^'
1462
+ else:
1463
+ alignment = b''
1464
+
1465
+ parts = [b"T{"]
1466
+ field = type.fields
1467
+
1468
+ while field.type:
1469
+ part = format_from_typeinfo(field.type)
1470
+ parts.append(part + b':' + field.name + b':')
1471
+ field += 1
1472
+
1473
+ result = alignment.join(parts) + b'}'
1474
+ else:
1475
+ fmt = __Pyx_TypeInfoToFormat(type)
1476
+ result = fmt.string
1477
+ if type.arraysize[0]:
1478
+ extents = [f"{type.arraysize[i]}" for i in range(type.ndim)]
1479
+ result = f"({u','.join(extents)})".encode('ascii') + result
1480
+
1481
+ return result
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/Profile.c ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////// Profile.proto ///////////////
2
+ //@requires: Exceptions.c::PyErrFetchRestore
3
+ //@substitute: naming
4
+
5
+ // Note that cPython ignores PyTrace_EXCEPTION,
6
+ // but maybe some other profilers don't.
7
+
8
+ #ifndef CYTHON_PROFILE
9
+ #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY
10
+ #define CYTHON_PROFILE 0
11
+ #else
12
+ #define CYTHON_PROFILE 1
13
+ #endif
14
+ #endif
15
+
16
+ #ifndef CYTHON_TRACE_NOGIL
17
+ #define CYTHON_TRACE_NOGIL 0
18
+ #else
19
+ #if CYTHON_TRACE_NOGIL && !defined(CYTHON_TRACE)
20
+ #define CYTHON_TRACE 1
21
+ #endif
22
+ #endif
23
+
24
+ #ifndef CYTHON_TRACE
25
+ #define CYTHON_TRACE 0
26
+ #endif
27
+
28
+ #if CYTHON_TRACE
29
+ #undef CYTHON_PROFILE_REUSE_FRAME
30
+ #endif
31
+
32
+ #ifndef CYTHON_PROFILE_REUSE_FRAME
33
+ #define CYTHON_PROFILE_REUSE_FRAME 0
34
+ #endif
35
+
36
+ #if CYTHON_PROFILE || CYTHON_TRACE
37
+
38
+ #include "compile.h"
39
+ #include "frameobject.h"
40
+ #include "traceback.h"
41
+ #if PY_VERSION_HEX >= 0x030b00a6
42
+ #ifndef Py_BUILD_CORE
43
+ #define Py_BUILD_CORE 1
44
+ #endif
45
+ #include "internal/pycore_frame.h"
46
+ #endif
47
+
48
+ #if CYTHON_PROFILE_REUSE_FRAME
49
+ #define CYTHON_FRAME_MODIFIER static
50
+ #define CYTHON_FRAME_DEL(frame)
51
+ #else
52
+ #define CYTHON_FRAME_MODIFIER
53
+ #define CYTHON_FRAME_DEL(frame) Py_CLEAR(frame)
54
+ #endif
55
+
56
+ #define __Pyx_TraceDeclarations \
57
+ static PyCodeObject *$frame_code_cname = NULL; \
58
+ CYTHON_FRAME_MODIFIER PyFrameObject *$frame_cname = NULL; \
59
+ int __Pyx_use_tracing = 0;
60
+
61
+ #define __Pyx_TraceFrameInit(codeobj) \
62
+ if (codeobj) $frame_code_cname = (PyCodeObject*) codeobj;
63
+
64
+
65
+ #if PY_VERSION_HEX >= 0x030b00a2
66
+ #if PY_VERSION_HEX >= 0x030C00b1
67
+ #define __Pyx_IsTracing(tstate, check_tracing, check_funcs) \
68
+ ((!(check_tracing) || !(tstate)->tracing) && \
69
+ (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc)))
70
+ #else
71
+ #define __Pyx_IsTracing(tstate, check_tracing, check_funcs) \
72
+ (unlikely((tstate)->cframe->use_tracing) && \
73
+ (!(check_tracing) || !(tstate)->tracing) && \
74
+ (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc)))
75
+ #endif
76
+
77
+ #define __Pyx_EnterTracing(tstate) PyThreadState_EnterTracing(tstate)
78
+ #define __Pyx_LeaveTracing(tstate) PyThreadState_LeaveTracing(tstate)
79
+
80
+ #elif PY_VERSION_HEX >= 0x030a00b1
81
+ #define __Pyx_IsTracing(tstate, check_tracing, check_funcs) \
82
+ (unlikely((tstate)->cframe->use_tracing) && \
83
+ (!(check_tracing) || !(tstate)->tracing) && \
84
+ (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc)))
85
+
86
+ #define __Pyx_EnterTracing(tstate) \
87
+ do { tstate->tracing++; tstate->cframe->use_tracing = 0; } while (0)
88
+
89
+ #define __Pyx_LeaveTracing(tstate) \
90
+ do { \
91
+ tstate->tracing--; \
92
+ tstate->cframe->use_tracing = ((CYTHON_TRACE && tstate->c_tracefunc != NULL) \
93
+ || tstate->c_profilefunc != NULL); \
94
+ } while (0)
95
+
96
+ #else
97
+ #define __Pyx_IsTracing(tstate, check_tracing, check_funcs) \
98
+ (unlikely((tstate)->use_tracing) && \
99
+ (!(check_tracing) || !(tstate)->tracing) && \
100
+ (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc)))
101
+
102
+ #define __Pyx_EnterTracing(tstate) \
103
+ do { tstate->tracing++; tstate->use_tracing = 0; } while (0)
104
+
105
+ #define __Pyx_LeaveTracing(tstate) \
106
+ do { \
107
+ tstate->tracing--; \
108
+ tstate->use_tracing = ((CYTHON_TRACE && tstate->c_tracefunc != NULL) \
109
+ || tstate->c_profilefunc != NULL); \
110
+ } while (0)
111
+
112
+ #endif
113
+
114
+ #ifdef WITH_THREAD
115
+ #define __Pyx_TraceCall(funcname, srcfile, firstlineno, nogil, goto_error) \
116
+ if (nogil) { \
117
+ if (CYTHON_TRACE_NOGIL) { \
118
+ PyThreadState *tstate; \
119
+ PyGILState_STATE state = PyGILState_Ensure(); \
120
+ tstate = __Pyx_PyThreadState_Current; \
121
+ if (__Pyx_IsTracing(tstate, 1, 1)) { \
122
+ __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&$frame_code_cname, &$frame_cname, tstate, funcname, srcfile, firstlineno); \
123
+ } \
124
+ PyGILState_Release(state); \
125
+ if (unlikely(__Pyx_use_tracing < 0)) goto_error; \
126
+ } \
127
+ } else { \
128
+ PyThreadState* tstate = PyThreadState_GET(); \
129
+ if (__Pyx_IsTracing(tstate, 1, 1)) { \
130
+ __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&$frame_code_cname, &$frame_cname, tstate, funcname, srcfile, firstlineno); \
131
+ if (unlikely(__Pyx_use_tracing < 0)) goto_error; \
132
+ } \
133
+ }
134
+ #else
135
+ #define __Pyx_TraceCall(funcname, srcfile, firstlineno, nogil, goto_error) \
136
+ { PyThreadState* tstate = PyThreadState_GET(); \
137
+ if (__Pyx_IsTracing(tstate, 1, 1)) { \
138
+ __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&$frame_code_cname, &$frame_cname, tstate, funcname, srcfile, firstlineno); \
139
+ if (unlikely(__Pyx_use_tracing < 0)) goto_error; \
140
+ } \
141
+ }
142
+ #endif
143
+
144
+ #define __Pyx_TraceException() \
145
+ if (likely(!__Pyx_use_tracing)); else { \
146
+ PyThreadState* tstate = __Pyx_PyThreadState_Current; \
147
+ if (__Pyx_IsTracing(tstate, 0, 1)) { \
148
+ __Pyx_EnterTracing(tstate); \
149
+ PyObject *exc_info = __Pyx_GetExceptionTuple(tstate); \
150
+ if (exc_info) { \
151
+ if (CYTHON_TRACE && tstate->c_tracefunc) \
152
+ tstate->c_tracefunc( \
153
+ tstate->c_traceobj, $frame_cname, PyTrace_EXCEPTION, exc_info); \
154
+ tstate->c_profilefunc( \
155
+ tstate->c_profileobj, $frame_cname, PyTrace_EXCEPTION, exc_info); \
156
+ Py_DECREF(exc_info); \
157
+ } \
158
+ __Pyx_LeaveTracing(tstate); \
159
+ } \
160
+ }
161
+
162
+ static void __Pyx_call_return_trace_func(PyThreadState *tstate, PyFrameObject *frame, PyObject *result) {
163
+ PyObject *type, *value, *traceback;
164
+ __Pyx_ErrFetchInState(tstate, &type, &value, &traceback);
165
+ __Pyx_EnterTracing(tstate);
166
+ if (CYTHON_TRACE && tstate->c_tracefunc)
167
+ tstate->c_tracefunc(tstate->c_traceobj, frame, PyTrace_RETURN, result);
168
+ if (tstate->c_profilefunc)
169
+ tstate->c_profilefunc(tstate->c_profileobj, frame, PyTrace_RETURN, result);
170
+ CYTHON_FRAME_DEL(frame);
171
+ __Pyx_LeaveTracing(tstate);
172
+ __Pyx_ErrRestoreInState(tstate, type, value, traceback);
173
+ }
174
+
175
+ #ifdef WITH_THREAD
176
+ #define __Pyx_TraceReturn(result, nogil) \
177
+ if (likely(!__Pyx_use_tracing)); else { \
178
+ if (nogil) { \
179
+ if (CYTHON_TRACE_NOGIL) { \
180
+ PyThreadState *tstate; \
181
+ PyGILState_STATE state = PyGILState_Ensure(); \
182
+ tstate = __Pyx_PyThreadState_Current; \
183
+ if (__Pyx_IsTracing(tstate, 0, 0)) { \
184
+ __Pyx_call_return_trace_func(tstate, $frame_cname, (PyObject*)result); \
185
+ } \
186
+ PyGILState_Release(state); \
187
+ } \
188
+ } else { \
189
+ PyThreadState* tstate = __Pyx_PyThreadState_Current; \
190
+ if (__Pyx_IsTracing(tstate, 0, 0)) { \
191
+ __Pyx_call_return_trace_func(tstate, $frame_cname, (PyObject*)result); \
192
+ } \
193
+ } \
194
+ }
195
+ #else
196
+ #define __Pyx_TraceReturn(result, nogil) \
197
+ if (likely(!__Pyx_use_tracing)); else { \
198
+ PyThreadState* tstate = __Pyx_PyThreadState_Current; \
199
+ if (__Pyx_IsTracing(tstate, 0, 0)) { \
200
+ __Pyx_call_return_trace_func(tstate, $frame_cname, (PyObject*)result); \
201
+ } \
202
+ }
203
+ #endif
204
+
205
+ static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/
206
+ static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, PyThreadState* tstate, const char *funcname, const char *srcfile, int firstlineno); /*proto*/
207
+
208
+ #else
209
+
210
+ #define __Pyx_TraceDeclarations
211
+ #define __Pyx_TraceFrameInit(codeobj)
212
+ // mark error label as used to avoid compiler warnings
213
+ #define __Pyx_TraceCall(funcname, srcfile, firstlineno, nogil, goto_error) if ((1)); else goto_error;
214
+ #define __Pyx_TraceException()
215
+ #define __Pyx_TraceReturn(result, nogil)
216
+
217
+ #endif /* CYTHON_PROFILE */
218
+
219
+ #if CYTHON_TRACE
220
+ // see call_trace_protected() in CPython's ceval.c
221
+ static int __Pyx_call_line_trace_func(PyThreadState *tstate, PyFrameObject *frame, int lineno) {
222
+ int ret;
223
+ PyObject *type, *value, *traceback;
224
+ __Pyx_ErrFetchInState(tstate, &type, &value, &traceback);
225
+ __Pyx_PyFrame_SetLineNumber(frame, lineno);
226
+ __Pyx_EnterTracing(tstate);
227
+
228
+ ret = tstate->c_tracefunc(tstate->c_traceobj, frame, PyTrace_LINE, NULL);
229
+
230
+ __Pyx_LeaveTracing(tstate);
231
+ if (likely(!ret)) {
232
+ __Pyx_ErrRestoreInState(tstate, type, value, traceback);
233
+ } else {
234
+ Py_XDECREF(type);
235
+ Py_XDECREF(value);
236
+ Py_XDECREF(traceback);
237
+ }
238
+ return ret;
239
+ }
240
+
241
+ #ifdef WITH_THREAD
242
+ #define __Pyx_TraceLine(lineno, nogil, goto_error) \
243
+ if (likely(!__Pyx_use_tracing)); else { \
244
+ if (nogil) { \
245
+ if (CYTHON_TRACE_NOGIL) { \
246
+ int ret = 0; \
247
+ PyThreadState *tstate; \
248
+ PyGILState_STATE state = __Pyx_PyGILState_Ensure(); \
249
+ tstate = __Pyx_PyThreadState_Current; \
250
+ if (__Pyx_IsTracing(tstate, 0, 0) && tstate->c_tracefunc && $frame_cname->f_trace) { \
251
+ ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \
252
+ } \
253
+ __Pyx_PyGILState_Release(state); \
254
+ if (unlikely(ret)) goto_error; \
255
+ } \
256
+ } else { \
257
+ PyThreadState* tstate = __Pyx_PyThreadState_Current; \
258
+ if (__Pyx_IsTracing(tstate, 0, 0) && tstate->c_tracefunc && $frame_cname->f_trace) { \
259
+ int ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \
260
+ if (unlikely(ret)) goto_error; \
261
+ } \
262
+ } \
263
+ }
264
+ #else
265
+ #define __Pyx_TraceLine(lineno, nogil, goto_error) \
266
+ if (likely(!__Pyx_use_tracing)); else { \
267
+ PyThreadState* tstate = __Pyx_PyThreadState_Current; \
268
+ if (__Pyx_IsTracing(tstate, 0, 0) && tstate->c_tracefunc && $frame_cname->f_trace) { \
269
+ int ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \
270
+ if (unlikely(ret)) goto_error; \
271
+ } \
272
+ }
273
+ #endif
274
+ #else
275
+ // mark error label as used to avoid compiler warnings
276
+ #define __Pyx_TraceLine(lineno, nogil, goto_error) if ((1)); else goto_error;
277
+ #endif
278
+
279
+ /////////////// Profile ///////////////
280
+ //@substitute: naming
281
+
282
+ #if CYTHON_PROFILE
283
+
284
+ static int __Pyx_TraceSetupAndCall(PyCodeObject** code,
285
+ PyFrameObject** frame,
286
+ PyThreadState* tstate,
287
+ const char *funcname,
288
+ const char *srcfile,
289
+ int firstlineno) {
290
+ PyObject *type, *value, *traceback;
291
+ int retval;
292
+ if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) {
293
+ if (*code == NULL) {
294
+ *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno);
295
+ if (*code == NULL) return 0;
296
+ }
297
+ *frame = PyFrame_New(
298
+ tstate, /*PyThreadState *tstate*/
299
+ *code, /*PyCodeObject *code*/
300
+ $moddict_cname, /*PyObject *globals*/
301
+ 0 /*PyObject *locals*/
302
+ );
303
+ if (*frame == NULL) return 0;
304
+ if (CYTHON_TRACE && (*frame)->f_trace == NULL) {
305
+ // this enables "f_lineno" lookup, at least in CPython ...
306
+ Py_INCREF(Py_None);
307
+ (*frame)->f_trace = Py_None;
308
+ }
309
+ #if PY_VERSION_HEX < 0x030400B1
310
+ } else {
311
+ (*frame)->f_tstate = tstate;
312
+ #endif
313
+ }
314
+ __Pyx_PyFrame_SetLineNumber(*frame, firstlineno);
315
+
316
+ retval = 1;
317
+ __Pyx_EnterTracing(tstate);
318
+ __Pyx_ErrFetchInState(tstate, &type, &value, &traceback);
319
+
320
+ #if CYTHON_TRACE
321
+ if (tstate->c_tracefunc)
322
+ retval = tstate->c_tracefunc(tstate->c_traceobj, *frame, PyTrace_CALL, NULL) == 0;
323
+ if (retval && tstate->c_profilefunc)
324
+ #endif
325
+ retval = tstate->c_profilefunc(tstate->c_profileobj, *frame, PyTrace_CALL, NULL) == 0;
326
+
327
+ __Pyx_LeaveTracing(tstate);
328
+ if (retval) {
329
+ __Pyx_ErrRestoreInState(tstate, type, value, traceback);
330
+ return __Pyx_IsTracing(tstate, 0, 0) && retval;
331
+ } else {
332
+ Py_XDECREF(type);
333
+ Py_XDECREF(value);
334
+ Py_XDECREF(traceback);
335
+ return -1;
336
+ }
337
+ }
338
+
339
+ static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) {
340
+ PyCodeObject *py_code = 0;
341
+
342
+ #if PY_MAJOR_VERSION >= 3
343
+ py_code = PyCode_NewEmpty(srcfile, funcname, firstlineno);
344
+ // make CPython use a fresh dict for "f_locals" at need (see GH #1836)
345
+ if (likely(py_code)) {
346
+ py_code->co_flags |= CO_OPTIMIZED | CO_NEWLOCALS;
347
+ }
348
+ #else
349
+ PyObject *py_srcfile = 0;
350
+ PyObject *py_funcname = 0;
351
+
352
+ py_funcname = PyString_FromString(funcname);
353
+ if (unlikely(!py_funcname)) goto bad;
354
+ py_srcfile = PyString_FromString(srcfile);
355
+ if (unlikely(!py_srcfile)) goto bad;
356
+
357
+ py_code = PyCode_New(
358
+ 0, /*int argcount,*/
359
+ 0, /*int nlocals,*/
360
+ 0, /*int stacksize,*/
361
+ // make CPython use a fresh dict for "f_locals" at need (see GH #1836)
362
+ CO_OPTIMIZED | CO_NEWLOCALS, /*int flags,*/
363
+ $empty_bytes, /*PyObject *code,*/
364
+ $empty_tuple, /*PyObject *consts,*/
365
+ $empty_tuple, /*PyObject *names,*/
366
+ $empty_tuple, /*PyObject *varnames,*/
367
+ $empty_tuple, /*PyObject *freevars,*/
368
+ $empty_tuple, /*PyObject *cellvars,*/
369
+ py_srcfile, /*PyObject *filename,*/
370
+ py_funcname, /*PyObject *name,*/
371
+ firstlineno, /*int firstlineno,*/
372
+ $empty_bytes /*PyObject *lnotab*/
373
+ );
374
+
375
+ bad:
376
+ Py_XDECREF(py_srcfile);
377
+ Py_XDECREF(py_funcname);
378
+ #endif
379
+
380
+ return py_code;
381
+ }
382
+
383
+ #endif /* CYTHON_PROFILE */
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/StringTools.c ADDED
@@ -0,0 +1,1294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ //////////////////// IncludeStringH.proto ////////////////////
3
+
4
+ #include <string.h>
5
+
6
+ //////////////////// IncludeCppStringH.proto ////////////////////
7
+
8
+ #include <string>
9
+
10
+
11
+ //////////////////// ssize_pyunicode_strlen.proto ////////////////////
12
+
13
+ static CYTHON_INLINE Py_ssize_t __Pyx_Py_UNICODE_ssize_strlen(const Py_UNICODE *u);/*proto*/
14
+
15
+ //////////////////// ssize_pyunicode_strlen ////////////////////
16
+ //@requires: pyunicode_strlen
17
+
18
+ static CYTHON_INLINE Py_ssize_t __Pyx_Py_UNICODE_ssize_strlen(const Py_UNICODE *u) {
19
+ size_t len = __Pyx_Py_UNICODE_strlen(u);
20
+ if (unlikely(len > PY_SSIZE_T_MAX)) {
21
+ PyErr_SetString(PyExc_OverflowError, "Py_UNICODE string is too long");
22
+ return -1;
23
+ }
24
+ return (Py_ssize_t) len;
25
+ }
26
+
27
+ //////////////////// pyunicode_strlen.proto ///////////////
28
+
29
+ // There used to be a Py_UNICODE_strlen() in CPython 3.x, but it is deprecated since Py3.3.
30
+ static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u); /* proto */
31
+
32
+ //////////////////// pyunicode_strlen /////////////////////
33
+
34
+ // Note: will not work in the limited API since Py_UNICODE is not available there.
35
+ // May stop working at some point after Python 3.13 (deprecated)
36
+ static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u)
37
+ {
38
+ const Py_UNICODE *u_end = u;
39
+ while (*u_end++) ;
40
+ return (size_t)(u_end - u - 1);
41
+ }
42
+
43
+ //////////////////// pyunicode_from_unicode.proto //////////////////////
44
+ //@requires: pyunicode_strlen
45
+
46
+ #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
47
+ #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
48
+
49
+ //////////////////// InitStrings.proto ////////////////////
50
+
51
+ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
52
+
53
+ //////////////////// InitStrings ////////////////////
54
+
55
+ #if PY_MAJOR_VERSION >= 3
56
+ static int __Pyx_InitString(__Pyx_StringTabEntry t, PyObject **str) {
57
+ if (t.is_unicode | t.is_str) {
58
+ if (t.intern) {
59
+ *str = PyUnicode_InternFromString(t.s);
60
+ } else if (t.encoding) {
61
+ *str = PyUnicode_Decode(t.s, t.n - 1, t.encoding, NULL);
62
+ } else {
63
+ *str = PyUnicode_FromStringAndSize(t.s, t.n - 1);
64
+ }
65
+ } else {
66
+ *str = PyBytes_FromStringAndSize(t.s, t.n - 1);
67
+ }
68
+ if (!*str)
69
+ return -1;
70
+ // initialise cached hash value
71
+ if (PyObject_Hash(*str) == -1)
72
+ return -1;
73
+ return 0;
74
+ }
75
+ #endif
76
+
77
+ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
78
+ while (t->p) {
79
+ #if PY_MAJOR_VERSION >= 3 /* Python 3+ has unicode identifiers */
80
+ __Pyx_InitString(*t, t->p);
81
+ #else
82
+ if (t->is_unicode) {
83
+ *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
84
+ } else if (t->intern) {
85
+ *t->p = PyString_InternFromString(t->s);
86
+ } else {
87
+ *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
88
+ }
89
+ if (!*t->p)
90
+ return -1;
91
+ // initialise cached hash value
92
+ if (PyObject_Hash(*t->p) == -1)
93
+ return -1;
94
+ #endif
95
+ ++t;
96
+ }
97
+ return 0;
98
+ }
99
+
100
+ //////////////////// BytesContains.proto ////////////////////
101
+
102
+ static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/
103
+
104
+ //////////////////// BytesContains ////////////////////
105
+ //@requires: IncludeStringH
106
+
107
+ static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) {
108
+ const Py_ssize_t length = PyBytes_GET_SIZE(bytes);
109
+ char* char_start = PyBytes_AS_STRING(bytes);
110
+ return memchr(char_start, (unsigned char)character, (size_t)length) != NULL;
111
+ }
112
+
113
+
114
+ //////////////////// PyUCS4InUnicode.proto ////////////////////
115
+
116
+ static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character); /*proto*/
117
+
118
+ //////////////////// PyUCS4InUnicode ////////////////////
119
+
120
+ #if PY_VERSION_HEX < 0x03090000 || (defined(PyUnicode_WCHAR_KIND) && defined(PyUnicode_AS_UNICODE))
121
+
122
+ #if PY_VERSION_HEX < 0x03090000
123
+ #define __Pyx_PyUnicode_AS_UNICODE(op) PyUnicode_AS_UNICODE(op)
124
+ #define __Pyx_PyUnicode_GET_SIZE(op) PyUnicode_GET_SIZE(op)
125
+ #else
126
+ // Avoid calling deprecated C-API functions in Py3.9+ that PEP-623 schedules for removal in Py3.12.
127
+ // https://www.python.org/dev/peps/pep-0623/
128
+ #define __Pyx_PyUnicode_AS_UNICODE(op) (((PyASCIIObject *)(op))->wstr)
129
+ #define __Pyx_PyUnicode_GET_SIZE(op) ((PyCompactUnicodeObject *)(op))->wstr_length
130
+ #endif
131
+
132
+ #if !defined(Py_UNICODE_SIZE) || Py_UNICODE_SIZE == 2
133
+ static int __Pyx_PyUnicodeBufferContainsUCS4_SP(Py_UNICODE* buffer, Py_ssize_t length, Py_UCS4 character) {
134
+ /* handle surrogate pairs for Py_UNICODE buffers in 16bit Unicode builds */
135
+ Py_UNICODE high_val, low_val;
136
+ Py_UNICODE* pos;
137
+ high_val = (Py_UNICODE) (0xD800 | (((character - 0x10000) >> 10) & ((1<<10)-1)));
138
+ low_val = (Py_UNICODE) (0xDC00 | ( (character - 0x10000) & ((1<<10)-1)));
139
+ for (pos=buffer; pos < buffer+length-1; pos++) {
140
+ if (unlikely((high_val == pos[0]) & (low_val == pos[1]))) return 1;
141
+ }
142
+ return 0;
143
+ }
144
+ #endif
145
+
146
+ static int __Pyx_PyUnicodeBufferContainsUCS4_BMP(Py_UNICODE* buffer, Py_ssize_t length, Py_UCS4 character) {
147
+ Py_UNICODE uchar;
148
+ Py_UNICODE* pos;
149
+ uchar = (Py_UNICODE) character;
150
+ for (pos=buffer; pos < buffer+length; pos++) {
151
+ if (unlikely(uchar == pos[0])) return 1;
152
+ }
153
+ return 0;
154
+ }
155
+ #endif
156
+
157
+ static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character) {
158
+ #if CYTHON_PEP393_ENABLED
159
+ const int kind = PyUnicode_KIND(unicode);
160
+ #ifdef PyUnicode_WCHAR_KIND
161
+ if (likely(kind != PyUnicode_WCHAR_KIND))
162
+ #endif
163
+ {
164
+ Py_ssize_t i;
165
+ const void* udata = PyUnicode_DATA(unicode);
166
+ const Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
167
+ for (i=0; i < length; i++) {
168
+ if (unlikely(character == PyUnicode_READ(kind, udata, i))) return 1;
169
+ }
170
+ return 0;
171
+ }
172
+ #elif PY_VERSION_HEX >= 0x03090000
173
+ #error Cannot use "UChar in Unicode" in Python 3.9 without PEP-393 unicode strings.
174
+ #elif !defined(PyUnicode_AS_UNICODE)
175
+ #error Cannot use "UChar in Unicode" in Python < 3.9 without Py_UNICODE support.
176
+ #endif
177
+
178
+ #if PY_VERSION_HEX < 0x03090000 || (defined(PyUnicode_WCHAR_KIND) && defined(PyUnicode_AS_UNICODE))
179
+ #if !defined(Py_UNICODE_SIZE) || Py_UNICODE_SIZE == 2
180
+ if ((sizeof(Py_UNICODE) == 2) && unlikely(character > 65535)) {
181
+ return __Pyx_PyUnicodeBufferContainsUCS4_SP(
182
+ __Pyx_PyUnicode_AS_UNICODE(unicode),
183
+ __Pyx_PyUnicode_GET_SIZE(unicode),
184
+ character);
185
+ } else
186
+ #endif
187
+ {
188
+ return __Pyx_PyUnicodeBufferContainsUCS4_BMP(
189
+ __Pyx_PyUnicode_AS_UNICODE(unicode),
190
+ __Pyx_PyUnicode_GET_SIZE(unicode),
191
+ character);
192
+
193
+ }
194
+ #endif
195
+ }
196
+
197
+
198
+ //////////////////// PyUnicodeContains.proto ////////////////////
199
+
200
+ static CYTHON_INLINE int __Pyx_PyUnicode_ContainsTF(PyObject* substring, PyObject* text, int eq) {
201
+ int result = PyUnicode_Contains(text, substring);
202
+ return unlikely(result < 0) ? result : (result == (eq == Py_EQ));
203
+ }
204
+
205
+
206
+ //////////////////// CStringEquals.proto ////////////////////
207
+
208
+ static CYTHON_INLINE int __Pyx_StrEq(const char *, const char *); /*proto*/
209
+
210
+ //////////////////// CStringEquals ////////////////////
211
+
212
+ static CYTHON_INLINE int __Pyx_StrEq(const char *s1, const char *s2) {
213
+ while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
214
+ return *s1 == *s2;
215
+ }
216
+
217
+
218
+ //////////////////// StrEquals.proto ////////////////////
219
+ //@requires: BytesEquals
220
+ //@requires: UnicodeEquals
221
+
222
+ #if PY_MAJOR_VERSION >= 3
223
+ #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals
224
+ #else
225
+ #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals
226
+ #endif
227
+
228
+
229
+ //////////////////// UnicodeEquals.proto ////////////////////
230
+
231
+ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
232
+
233
+ //////////////////// UnicodeEquals ////////////////////
234
+ //@requires: BytesEquals
235
+
236
+ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
237
+ #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API
238
+ return PyObject_RichCompareBool(s1, s2, equals);
239
+ #else
240
+ #if PY_MAJOR_VERSION < 3
241
+ PyObject* owned_ref = NULL;
242
+ #endif
243
+ int s1_is_unicode, s2_is_unicode;
244
+ if (s1 == s2) {
245
+ /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
246
+ goto return_eq;
247
+ }
248
+ s1_is_unicode = PyUnicode_CheckExact(s1);
249
+ s2_is_unicode = PyUnicode_CheckExact(s2);
250
+ #if PY_MAJOR_VERSION < 3
251
+ if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) {
252
+ owned_ref = PyUnicode_FromObject(s2);
253
+ if (unlikely(!owned_ref))
254
+ return -1;
255
+ s2 = owned_ref;
256
+ s2_is_unicode = 1;
257
+ } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) {
258
+ owned_ref = PyUnicode_FromObject(s1);
259
+ if (unlikely(!owned_ref))
260
+ return -1;
261
+ s1 = owned_ref;
262
+ s1_is_unicode = 1;
263
+ } else if (((!s2_is_unicode) & (!s1_is_unicode))) {
264
+ return __Pyx_PyBytes_Equals(s1, s2, equals);
265
+ }
266
+ #endif
267
+ if (s1_is_unicode & s2_is_unicode) {
268
+ Py_ssize_t length;
269
+ int kind;
270
+ void *data1, *data2;
271
+ if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0))
272
+ return -1;
273
+ length = __Pyx_PyUnicode_GET_LENGTH(s1);
274
+ if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) {
275
+ goto return_ne;
276
+ }
277
+ #if CYTHON_USE_UNICODE_INTERNALS
278
+ {
279
+ Py_hash_t hash1, hash2;
280
+ #if CYTHON_PEP393_ENABLED
281
+ hash1 = ((PyASCIIObject*)s1)->hash;
282
+ hash2 = ((PyASCIIObject*)s2)->hash;
283
+ #else
284
+ hash1 = ((PyUnicodeObject*)s1)->hash;
285
+ hash2 = ((PyUnicodeObject*)s2)->hash;
286
+ #endif
287
+ if (hash1 != hash2 && hash1 != -1 && hash2 != -1) {
288
+ goto return_ne;
289
+ }
290
+ }
291
+ #endif
292
+ // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2")
293
+ kind = __Pyx_PyUnicode_KIND(s1);
294
+ if (kind != __Pyx_PyUnicode_KIND(s2)) {
295
+ goto return_ne;
296
+ }
297
+ data1 = __Pyx_PyUnicode_DATA(s1);
298
+ data2 = __Pyx_PyUnicode_DATA(s2);
299
+ if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) {
300
+ goto return_ne;
301
+ } else if (length == 1) {
302
+ goto return_eq;
303
+ } else {
304
+ int result = memcmp(data1, data2, (size_t)(length * kind));
305
+ #if PY_MAJOR_VERSION < 3
306
+ Py_XDECREF(owned_ref);
307
+ #endif
308
+ return (equals == Py_EQ) ? (result == 0) : (result != 0);
309
+ }
310
+ } else if ((s1 == Py_None) & s2_is_unicode) {
311
+ goto return_ne;
312
+ } else if ((s2 == Py_None) & s1_is_unicode) {
313
+ goto return_ne;
314
+ } else {
315
+ int result;
316
+ PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
317
+ #if PY_MAJOR_VERSION < 3
318
+ Py_XDECREF(owned_ref);
319
+ #endif
320
+ if (!py_result)
321
+ return -1;
322
+ result = __Pyx_PyObject_IsTrue(py_result);
323
+ Py_DECREF(py_result);
324
+ return result;
325
+ }
326
+ return_eq:
327
+ #if PY_MAJOR_VERSION < 3
328
+ Py_XDECREF(owned_ref);
329
+ #endif
330
+ return (equals == Py_EQ);
331
+ return_ne:
332
+ #if PY_MAJOR_VERSION < 3
333
+ Py_XDECREF(owned_ref);
334
+ #endif
335
+ return (equals == Py_NE);
336
+ #endif
337
+ }
338
+
339
+
340
+ //////////////////// BytesEquals.proto ////////////////////
341
+
342
+ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
343
+
344
+ //////////////////// BytesEquals ////////////////////
345
+ //@requires: IncludeStringH
346
+
347
+ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) {
348
+ #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API
349
+ return PyObject_RichCompareBool(s1, s2, equals);
350
+ #else
351
+ if (s1 == s2) {
352
+ /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
353
+ return (equals == Py_EQ);
354
+ } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) {
355
+ const char *ps1, *ps2;
356
+ Py_ssize_t length = PyBytes_GET_SIZE(s1);
357
+ if (length != PyBytes_GET_SIZE(s2))
358
+ return (equals == Py_NE);
359
+ // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2")
360
+ ps1 = PyBytes_AS_STRING(s1);
361
+ ps2 = PyBytes_AS_STRING(s2);
362
+ if (ps1[0] != ps2[0]) {
363
+ return (equals == Py_NE);
364
+ } else if (length == 1) {
365
+ return (equals == Py_EQ);
366
+ } else {
367
+ int result;
368
+ #if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000)
369
+ Py_hash_t hash1, hash2;
370
+ hash1 = ((PyBytesObject*)s1)->ob_shash;
371
+ hash2 = ((PyBytesObject*)s2)->ob_shash;
372
+ if (hash1 != hash2 && hash1 != -1 && hash2 != -1) {
373
+ return (equals == Py_NE);
374
+ }
375
+ #endif
376
+ result = memcmp(ps1, ps2, (size_t)length);
377
+ return (equals == Py_EQ) ? (result == 0) : (result != 0);
378
+ }
379
+ } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) {
380
+ return (equals == Py_NE);
381
+ } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) {
382
+ return (equals == Py_NE);
383
+ } else {
384
+ int result;
385
+ PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
386
+ if (!py_result)
387
+ return -1;
388
+ result = __Pyx_PyObject_IsTrue(py_result);
389
+ Py_DECREF(py_result);
390
+ return result;
391
+ }
392
+ #endif
393
+ }
394
+
395
+ //////////////////// GetItemIntByteArray.proto ////////////////////
396
+
397
+ #define __Pyx_GetItemInt_ByteArray(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
398
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
399
+ __Pyx_GetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \
400
+ (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1))
401
+
402
+ static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i,
403
+ int wraparound, int boundscheck);
404
+
405
+ //////////////////// GetItemIntByteArray ////////////////////
406
+
407
+ static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i,
408
+ int wraparound, int boundscheck) {
409
+ Py_ssize_t length;
410
+ if (wraparound | boundscheck) {
411
+ length = PyByteArray_GET_SIZE(string);
412
+ if (wraparound & unlikely(i < 0)) i += length;
413
+ if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) {
414
+ return (unsigned char) (PyByteArray_AS_STRING(string)[i]);
415
+ } else {
416
+ PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
417
+ return -1;
418
+ }
419
+ } else {
420
+ return (unsigned char) (PyByteArray_AS_STRING(string)[i]);
421
+ }
422
+ }
423
+
424
+
425
+ //////////////////// SetItemIntByteArray.proto ////////////////////
426
+
427
+ #define __Pyx_SetItemInt_ByteArray(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
428
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
429
+ __Pyx_SetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, v, wraparound, boundscheck) : \
430
+ (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1))
431
+
432
+ static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v,
433
+ int wraparound, int boundscheck);
434
+
435
+ //////////////////// SetItemIntByteArray ////////////////////
436
+
437
+ static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v,
438
+ int wraparound, int boundscheck) {
439
+ Py_ssize_t length;
440
+ if (wraparound | boundscheck) {
441
+ length = PyByteArray_GET_SIZE(string);
442
+ if (wraparound & unlikely(i < 0)) i += length;
443
+ if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) {
444
+ PyByteArray_AS_STRING(string)[i] = (char) v;
445
+ return 0;
446
+ } else {
447
+ PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
448
+ return -1;
449
+ }
450
+ } else {
451
+ PyByteArray_AS_STRING(string)[i] = (char) v;
452
+ return 0;
453
+ }
454
+ }
455
+
456
+
457
+ //////////////////// GetItemIntUnicode.proto ////////////////////
458
+
459
+ #define __Pyx_GetItemInt_Unicode(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
460
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
461
+ __Pyx_GetItemInt_Unicode_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \
462
+ (PyErr_SetString(PyExc_IndexError, "string index out of range"), (Py_UCS4)-1))
463
+
464
+ static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i,
465
+ int wraparound, int boundscheck);
466
+
467
+ //////////////////// GetItemIntUnicode ////////////////////
468
+
469
+ static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i,
470
+ int wraparound, int boundscheck) {
471
+ Py_ssize_t length;
472
+ if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return (Py_UCS4)-1;
473
+ if (wraparound | boundscheck) {
474
+ length = __Pyx_PyUnicode_GET_LENGTH(ustring);
475
+ if (wraparound & unlikely(i < 0)) i += length;
476
+ if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) {
477
+ return __Pyx_PyUnicode_READ_CHAR(ustring, i);
478
+ } else {
479
+ PyErr_SetString(PyExc_IndexError, "string index out of range");
480
+ return (Py_UCS4)-1;
481
+ }
482
+ } else {
483
+ return __Pyx_PyUnicode_READ_CHAR(ustring, i);
484
+ }
485
+ }
486
+
487
+
488
+ /////////////// decode_c_string_utf16.proto ///////////////
489
+
490
+ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) {
491
+ int byteorder = 0;
492
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
493
+ }
494
+ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) {
495
+ int byteorder = -1;
496
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
497
+ }
498
+ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) {
499
+ int byteorder = 1;
500
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
501
+ }
502
+
503
+ /////////////// decode_cpp_string.proto ///////////////
504
+ //@requires: IncludeCppStringH
505
+ //@requires: decode_c_bytes
506
+
507
+ static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string(
508
+ std::string cppstring, Py_ssize_t start, Py_ssize_t stop,
509
+ const char* encoding, const char* errors,
510
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
511
+ return __Pyx_decode_c_bytes(
512
+ cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func);
513
+ }
514
+
515
+ /////////////// decode_c_string.proto ///////////////
516
+
517
+ static CYTHON_INLINE PyObject* __Pyx_decode_c_string(
518
+ const char* cstring, Py_ssize_t start, Py_ssize_t stop,
519
+ const char* encoding, const char* errors,
520
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors));
521
+
522
+ /////////////// decode_c_string ///////////////
523
+ //@requires: IncludeStringH
524
+ //@requires: decode_c_string_utf16
525
+ //@substitute: naming
526
+
527
+ /* duplicate code to avoid calling strlen() if start >= 0 and stop >= 0 */
528
+ static CYTHON_INLINE PyObject* __Pyx_decode_c_string(
529
+ const char* cstring, Py_ssize_t start, Py_ssize_t stop,
530
+ const char* encoding, const char* errors,
531
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
532
+ Py_ssize_t length;
533
+ if (unlikely((start < 0) | (stop < 0))) {
534
+ size_t slen = strlen(cstring);
535
+ if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) {
536
+ PyErr_SetString(PyExc_OverflowError,
537
+ "c-string too long to convert to Python");
538
+ return NULL;
539
+ }
540
+ length = (Py_ssize_t) slen;
541
+ if (start < 0) {
542
+ start += length;
543
+ if (start < 0)
544
+ start = 0;
545
+ }
546
+ if (stop < 0)
547
+ stop += length;
548
+ }
549
+ if (unlikely(stop <= start))
550
+ return __Pyx_NewRef($empty_unicode);
551
+ length = stop - start;
552
+ cstring += start;
553
+ if (decode_func) {
554
+ return decode_func(cstring, length, errors);
555
+ } else {
556
+ return PyUnicode_Decode(cstring, length, encoding, errors);
557
+ }
558
+ }
559
+
560
+ /////////////// decode_c_bytes.proto ///////////////
561
+
562
+ static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes(
563
+ const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop,
564
+ const char* encoding, const char* errors,
565
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors));
566
+
567
+ /////////////// decode_c_bytes ///////////////
568
+ //@requires: decode_c_string_utf16
569
+ //@substitute: naming
570
+
571
+ static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes(
572
+ const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop,
573
+ const char* encoding, const char* errors,
574
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
575
+ if (unlikely((start < 0) | (stop < 0))) {
576
+ if (start < 0) {
577
+ start += length;
578
+ if (start < 0)
579
+ start = 0;
580
+ }
581
+ if (stop < 0)
582
+ stop += length;
583
+ }
584
+ if (stop > length)
585
+ stop = length;
586
+ if (unlikely(stop <= start))
587
+ return __Pyx_NewRef($empty_unicode);
588
+ length = stop - start;
589
+ cstring += start;
590
+ if (decode_func) {
591
+ return decode_func(cstring, length, errors);
592
+ } else {
593
+ return PyUnicode_Decode(cstring, length, encoding, errors);
594
+ }
595
+ }
596
+
597
+ /////////////// decode_bytes.proto ///////////////
598
+ //@requires: decode_c_bytes
599
+
600
+ static CYTHON_INLINE PyObject* __Pyx_decode_bytes(
601
+ PyObject* string, Py_ssize_t start, Py_ssize_t stop,
602
+ const char* encoding, const char* errors,
603
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
604
+ char* as_c_string;
605
+ Py_ssize_t size;
606
+ #if CYTHON_ASSUME_SAFE_MACROS
607
+ as_c_string = PyBytes_AS_STRING(string);
608
+ size = PyBytes_GET_SIZE(string);
609
+ #else
610
+ if (PyBytes_AsStringAndSize(string, &as_c_string, &size) < 0) {
611
+ return NULL;
612
+ }
613
+ #endif
614
+ return __Pyx_decode_c_bytes(
615
+ as_c_string, size,
616
+ start, stop, encoding, errors, decode_func);
617
+ }
618
+
619
+ /////////////// decode_bytearray.proto ///////////////
620
+ //@requires: decode_c_bytes
621
+
622
+ static CYTHON_INLINE PyObject* __Pyx_decode_bytearray(
623
+ PyObject* string, Py_ssize_t start, Py_ssize_t stop,
624
+ const char* encoding, const char* errors,
625
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
626
+ char* as_c_string;
627
+ Py_ssize_t size;
628
+ #if CYTHON_ASSUME_SAFE_MACROS
629
+ as_c_string = PyByteArray_AS_STRING(string);
630
+ size = PyByteArray_GET_SIZE(string);
631
+ #else
632
+ if (!(as_c_string = PyByteArray_AsString(string))) return NULL;
633
+ if ((size = PyByteArray_Size(string)) < 0) return NULL;
634
+ #endif
635
+ return __Pyx_decode_c_bytes(
636
+ as_c_string, size,
637
+ start, stop, encoding, errors, decode_func);
638
+ }
639
+
640
+ /////////////// PyUnicode_Substring.proto ///////////////
641
+
642
+ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring(
643
+ PyObject* text, Py_ssize_t start, Py_ssize_t stop);
644
+
645
+ /////////////// PyUnicode_Substring ///////////////
646
+ //@substitute: naming
647
+
648
+ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring(
649
+ PyObject* text, Py_ssize_t start, Py_ssize_t stop) {
650
+ Py_ssize_t length;
651
+ if (unlikely(__Pyx_PyUnicode_READY(text) == -1)) return NULL;
652
+ length = __Pyx_PyUnicode_GET_LENGTH(text);
653
+ if (start < 0) {
654
+ start += length;
655
+ if (start < 0)
656
+ start = 0;
657
+ }
658
+ if (stop < 0)
659
+ stop += length;
660
+ else if (stop > length)
661
+ stop = length;
662
+ if (stop <= start)
663
+ return __Pyx_NewRef($empty_unicode);
664
+ if (start == 0 && stop == length)
665
+ return __Pyx_NewRef(text);
666
+ #if CYTHON_PEP393_ENABLED
667
+ return PyUnicode_FromKindAndData(PyUnicode_KIND(text),
668
+ PyUnicode_1BYTE_DATA(text) + start*PyUnicode_KIND(text), stop-start);
669
+ #else
670
+ return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(text)+start, stop-start);
671
+ #endif
672
+ }
673
+
674
+
675
+ /////////////// py_unicode_istitle.proto ///////////////
676
+
677
+ // Py_UNICODE_ISTITLE() doesn't match unicode.istitle() as the latter
678
+ // additionally allows character that comply with Py_UNICODE_ISUPPER()
679
+
680
+ #if PY_VERSION_HEX < 0x030200A2
681
+ static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UNICODE uchar)
682
+ #else
683
+ static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UCS4 uchar)
684
+ #endif
685
+ {
686
+ return Py_UNICODE_ISTITLE(uchar) || Py_UNICODE_ISUPPER(uchar);
687
+ }
688
+
689
+
690
+ /////////////// unicode_tailmatch.proto ///////////////
691
+
692
+ static int __Pyx_PyUnicode_Tailmatch(
693
+ PyObject* s, PyObject* substr, Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/
694
+
695
+ /////////////// unicode_tailmatch ///////////////
696
+
697
+ // Python's unicode.startswith() and unicode.endswith() support a
698
+ // tuple of prefixes/suffixes, whereas it's much more common to
699
+ // test for a single unicode string.
700
+
701
+ static int __Pyx_PyUnicode_TailmatchTuple(PyObject* s, PyObject* substrings,
702
+ Py_ssize_t start, Py_ssize_t end, int direction) {
703
+ Py_ssize_t i, count = PyTuple_GET_SIZE(substrings);
704
+ for (i = 0; i < count; i++) {
705
+ Py_ssize_t result;
706
+ #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
707
+ result = PyUnicode_Tailmatch(s, PyTuple_GET_ITEM(substrings, i),
708
+ start, end, direction);
709
+ #else
710
+ PyObject* sub = PySequence_ITEM(substrings, i);
711
+ if (unlikely(!sub)) return -1;
712
+ result = PyUnicode_Tailmatch(s, sub, start, end, direction);
713
+ Py_DECREF(sub);
714
+ #endif
715
+ if (result) {
716
+ return (int) result;
717
+ }
718
+ }
719
+ return 0;
720
+ }
721
+
722
+ static int __Pyx_PyUnicode_Tailmatch(PyObject* s, PyObject* substr,
723
+ Py_ssize_t start, Py_ssize_t end, int direction) {
724
+ if (unlikely(PyTuple_Check(substr))) {
725
+ return __Pyx_PyUnicode_TailmatchTuple(s, substr, start, end, direction);
726
+ }
727
+ return (int) PyUnicode_Tailmatch(s, substr, start, end, direction);
728
+ }
729
+
730
+
731
+ /////////////// bytes_tailmatch.proto ///////////////
732
+
733
+ static int __Pyx_PyBytes_SingleTailmatch(PyObject* self, PyObject* arg,
734
+ Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/
735
+ static int __Pyx_PyBytes_Tailmatch(PyObject* self, PyObject* substr,
736
+ Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/
737
+
738
+ /////////////// bytes_tailmatch ///////////////
739
+
740
+ static int __Pyx_PyBytes_SingleTailmatch(PyObject* self, PyObject* arg,
741
+ Py_ssize_t start, Py_ssize_t end, int direction) {
742
+ const char* self_ptr = PyBytes_AS_STRING(self);
743
+ Py_ssize_t self_len = PyBytes_GET_SIZE(self);
744
+ const char* sub_ptr;
745
+ Py_ssize_t sub_len;
746
+ int retval;
747
+
748
+ Py_buffer view;
749
+ view.obj = NULL;
750
+
751
+ if ( PyBytes_Check(arg) ) {
752
+ sub_ptr = PyBytes_AS_STRING(arg);
753
+ sub_len = PyBytes_GET_SIZE(arg);
754
+ }
755
+ #if PY_MAJOR_VERSION < 3
756
+ // Python 2.x allows mixing unicode and str
757
+ else if ( PyUnicode_Check(arg) ) {
758
+ return (int) PyUnicode_Tailmatch(self, arg, start, end, direction);
759
+ }
760
+ #endif
761
+ else {
762
+ if (unlikely(PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) == -1))
763
+ return -1;
764
+ sub_ptr = (const char*) view.buf;
765
+ sub_len = view.len;
766
+ }
767
+
768
+ if (end > self_len)
769
+ end = self_len;
770
+ else if (end < 0)
771
+ end += self_len;
772
+ if (end < 0)
773
+ end = 0;
774
+ if (start < 0)
775
+ start += self_len;
776
+ if (start < 0)
777
+ start = 0;
778
+
779
+ if (direction > 0) {
780
+ /* endswith */
781
+ if (end-sub_len > start)
782
+ start = end - sub_len;
783
+ }
784
+
785
+ if (start + sub_len <= end)
786
+ retval = !memcmp(self_ptr+start, sub_ptr, (size_t)sub_len);
787
+ else
788
+ retval = 0;
789
+
790
+ if (view.obj)
791
+ PyBuffer_Release(&view);
792
+
793
+ return retval;
794
+ }
795
+
796
+ static int __Pyx_PyBytes_TailmatchTuple(PyObject* self, PyObject* substrings,
797
+ Py_ssize_t start, Py_ssize_t end, int direction) {
798
+ Py_ssize_t i, count = PyTuple_GET_SIZE(substrings);
799
+ for (i = 0; i < count; i++) {
800
+ int result;
801
+ #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
802
+ result = __Pyx_PyBytes_SingleTailmatch(self, PyTuple_GET_ITEM(substrings, i),
803
+ start, end, direction);
804
+ #else
805
+ PyObject* sub = PySequence_ITEM(substrings, i);
806
+ if (unlikely(!sub)) return -1;
807
+ result = __Pyx_PyBytes_SingleTailmatch(self, sub, start, end, direction);
808
+ Py_DECREF(sub);
809
+ #endif
810
+ if (result) {
811
+ return result;
812
+ }
813
+ }
814
+ return 0;
815
+ }
816
+
817
+ static int __Pyx_PyBytes_Tailmatch(PyObject* self, PyObject* substr,
818
+ Py_ssize_t start, Py_ssize_t end, int direction) {
819
+ if (unlikely(PyTuple_Check(substr))) {
820
+ return __Pyx_PyBytes_TailmatchTuple(self, substr, start, end, direction);
821
+ }
822
+
823
+ return __Pyx_PyBytes_SingleTailmatch(self, substr, start, end, direction);
824
+ }
825
+
826
+
827
+ /////////////// str_tailmatch.proto ///////////////
828
+
829
+ static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start,
830
+ Py_ssize_t end, int direction); /*proto*/
831
+
832
+ /////////////// str_tailmatch ///////////////
833
+ //@requires: bytes_tailmatch
834
+ //@requires: unicode_tailmatch
835
+
836
+ static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start,
837
+ Py_ssize_t end, int direction)
838
+ {
839
+ // We do not use a C compiler macro here to avoid "unused function"
840
+ // warnings for the *_Tailmatch() function that is not being used in
841
+ // the specific CPython version. The C compiler will generate the same
842
+ // code anyway, and will usually just remove the unused function.
843
+ if (PY_MAJOR_VERSION < 3)
844
+ return __Pyx_PyBytes_Tailmatch(self, arg, start, end, direction);
845
+ else
846
+ return __Pyx_PyUnicode_Tailmatch(self, arg, start, end, direction);
847
+ }
848
+
849
+
850
+ /////////////// bytes_index.proto ///////////////
851
+
852
+ static CYTHON_INLINE char __Pyx_PyBytes_GetItemInt(PyObject* bytes, Py_ssize_t index, int check_bounds); /*proto*/
853
+
854
+ /////////////// bytes_index ///////////////
855
+
856
+ static CYTHON_INLINE char __Pyx_PyBytes_GetItemInt(PyObject* bytes, Py_ssize_t index, int check_bounds) {
857
+ if (index < 0)
858
+ index += PyBytes_GET_SIZE(bytes);
859
+ if (check_bounds) {
860
+ Py_ssize_t size = PyBytes_GET_SIZE(bytes);
861
+ if (unlikely(!__Pyx_is_valid_index(index, size))) {
862
+ PyErr_SetString(PyExc_IndexError, "string index out of range");
863
+ return (char) -1;
864
+ }
865
+ }
866
+ return PyBytes_AS_STRING(bytes)[index];
867
+ }
868
+
869
+
870
+ //////////////////// StringJoin.proto ////////////////////
871
+
872
+ #if PY_MAJOR_VERSION < 3
873
+ #define __Pyx_PyString_Join __Pyx_PyBytes_Join
874
+ #define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v))
875
+ #else
876
+ #define __Pyx_PyString_Join PyUnicode_Join
877
+ #define __Pyx_PyBaseString_Join PyUnicode_Join
878
+ #endif
879
+ static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); /*proto*/
880
+
881
+ //////////////////// StringJoin ////////////////////
882
+ //@requires: ObjectHandling.c::PyObjectCallMethod1
883
+
884
+ static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) {
885
+ // avoid unused function
886
+ (void) __Pyx_PyObject_CallMethod1;
887
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION < 3
888
+ return _PyString_Join(sep, values);
889
+ #elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000
890
+ return _PyBytes_Join(sep, values);
891
+ #else
892
+ return __Pyx_PyObject_CallMethod1(sep, PYIDENT("join"), values);
893
+ #endif
894
+ }
895
+
896
+
897
+ /////////////// JoinPyUnicode.proto ///////////////
898
+
899
+ static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength,
900
+ Py_UCS4 max_char);
901
+
902
+ /////////////// JoinPyUnicode ///////////////
903
+ //@requires: IncludeStringH
904
+ //@substitute: naming
905
+
906
+ static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength,
907
+ Py_UCS4 max_char) {
908
+ #if CYTHON_USE_UNICODE_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
909
+ PyObject *result_uval;
910
+ int result_ukind, kind_shift;
911
+ Py_ssize_t i, char_pos;
912
+ void *result_udata;
913
+ CYTHON_MAYBE_UNUSED_VAR(max_char);
914
+ #if CYTHON_PEP393_ENABLED
915
+ // Py 3.3+ (post PEP-393)
916
+ result_uval = PyUnicode_New(result_ulength, max_char);
917
+ if (unlikely(!result_uval)) return NULL;
918
+ result_ukind = (max_char <= 255) ? PyUnicode_1BYTE_KIND : (max_char <= 65535) ? PyUnicode_2BYTE_KIND : PyUnicode_4BYTE_KIND;
919
+ kind_shift = (result_ukind == PyUnicode_4BYTE_KIND) ? 2 : result_ukind - 1;
920
+ result_udata = PyUnicode_DATA(result_uval);
921
+ #else
922
+ // Py 2.x/3.2 (pre PEP-393)
923
+ result_uval = PyUnicode_FromUnicode(NULL, result_ulength);
924
+ if (unlikely(!result_uval)) return NULL;
925
+ result_ukind = sizeof(Py_UNICODE);
926
+ kind_shift = (result_ukind == 4) ? 2 : result_ukind - 1;
927
+ result_udata = PyUnicode_AS_UNICODE(result_uval);
928
+ #endif
929
+ assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0);
930
+
931
+ char_pos = 0;
932
+ for (i=0; i < value_count; i++) {
933
+ int ukind;
934
+ Py_ssize_t ulength;
935
+ void *udata;
936
+ PyObject *uval = PyTuple_GET_ITEM(value_tuple, i);
937
+ if (unlikely(__Pyx_PyUnicode_READY(uval)))
938
+ goto bad;
939
+ ulength = __Pyx_PyUnicode_GET_LENGTH(uval);
940
+ if (unlikely(!ulength))
941
+ continue;
942
+ if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos))
943
+ goto overflow;
944
+ ukind = __Pyx_PyUnicode_KIND(uval);
945
+ udata = __Pyx_PyUnicode_DATA(uval);
946
+ if (!CYTHON_PEP393_ENABLED || ukind == result_ukind) {
947
+ memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift));
948
+ } else {
949
+ #if PY_VERSION_HEX >= 0x030d0000
950
+ if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad;
951
+ #elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030300F0 || defined(_PyUnicode_FastCopyCharacters)
952
+ _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength);
953
+ #else
954
+ Py_ssize_t j;
955
+ for (j=0; j < ulength; j++) {
956
+ Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j);
957
+ __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar);
958
+ }
959
+ #endif
960
+ }
961
+ char_pos += ulength;
962
+ }
963
+ return result_uval;
964
+ overflow:
965
+ PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string");
966
+ bad:
967
+ Py_DECREF(result_uval);
968
+ return NULL;
969
+ #else
970
+ // non-CPython fallback
971
+ CYTHON_UNUSED_VAR(max_char);
972
+ CYTHON_UNUSED_VAR(result_ulength);
973
+ CYTHON_UNUSED_VAR(value_count);
974
+ return PyUnicode_Join($empty_unicode, value_tuple);
975
+ #endif
976
+ }
977
+
978
+
979
+ /////////////// BuildPyUnicode.proto ///////////////
980
+
981
+ static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength,
982
+ int prepend_sign, char padding_char);
983
+
984
+ /////////////// BuildPyUnicode ///////////////
985
+
986
+ // Create a PyUnicode object from an ASCII char*, e.g. a formatted number.
987
+
988
+ static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength,
989
+ int prepend_sign, char padding_char) {
990
+ PyObject *uval;
991
+ Py_ssize_t uoffset = ulength - clength;
992
+ #if CYTHON_USE_UNICODE_INTERNALS
993
+ Py_ssize_t i;
994
+ #if CYTHON_PEP393_ENABLED
995
+ // Py 3.3+ (post PEP-393)
996
+ void *udata;
997
+ uval = PyUnicode_New(ulength, 127);
998
+ if (unlikely(!uval)) return NULL;
999
+ udata = PyUnicode_DATA(uval);
1000
+ #else
1001
+ // Py 2.x/3.2 (pre PEP-393)
1002
+ Py_UNICODE *udata;
1003
+ uval = PyUnicode_FromUnicode(NULL, ulength);
1004
+ if (unlikely(!uval)) return NULL;
1005
+ udata = PyUnicode_AS_UNICODE(uval);
1006
+ #endif
1007
+ if (uoffset > 0) {
1008
+ i = 0;
1009
+ if (prepend_sign) {
1010
+ __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, 0, '-');
1011
+ i++;
1012
+ }
1013
+ for (; i < uoffset; i++) {
1014
+ __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, i, padding_char);
1015
+ }
1016
+ }
1017
+ for (i=0; i < clength; i++) {
1018
+ __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, uoffset+i, chars[i]);
1019
+ }
1020
+
1021
+ #else
1022
+ // non-CPython
1023
+ {
1024
+ PyObject *sign = NULL, *padding = NULL;
1025
+ uval = NULL;
1026
+ if (uoffset > 0) {
1027
+ prepend_sign = !!prepend_sign;
1028
+ if (uoffset > prepend_sign) {
1029
+ padding = PyUnicode_FromOrdinal(padding_char);
1030
+ if (likely(padding) && uoffset > prepend_sign + 1) {
1031
+ PyObject *tmp;
1032
+ PyObject *repeat = PyInt_FromSsize_t(uoffset - prepend_sign);
1033
+ if (unlikely(!repeat)) goto done_or_error;
1034
+ tmp = PyNumber_Multiply(padding, repeat);
1035
+ Py_DECREF(repeat);
1036
+ Py_DECREF(padding);
1037
+ padding = tmp;
1038
+ }
1039
+ if (unlikely(!padding)) goto done_or_error;
1040
+ }
1041
+ if (prepend_sign) {
1042
+ sign = PyUnicode_FromOrdinal('-');
1043
+ if (unlikely(!sign)) goto done_or_error;
1044
+ }
1045
+ }
1046
+
1047
+ uval = PyUnicode_DecodeASCII(chars, clength, NULL);
1048
+ if (likely(uval) && padding) {
1049
+ PyObject *tmp = PyNumber_Add(padding, uval);
1050
+ Py_DECREF(uval);
1051
+ uval = tmp;
1052
+ }
1053
+ if (likely(uval) && sign) {
1054
+ PyObject *tmp = PyNumber_Add(sign, uval);
1055
+ Py_DECREF(uval);
1056
+ uval = tmp;
1057
+ }
1058
+ done_or_error:
1059
+ Py_XDECREF(padding);
1060
+ Py_XDECREF(sign);
1061
+ }
1062
+ #endif
1063
+
1064
+ return uval;
1065
+ }
1066
+
1067
+
1068
+ //////////////////// ByteArrayAppendObject.proto ////////////////////
1069
+
1070
+ static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value);
1071
+
1072
+ //////////////////// ByteArrayAppendObject ////////////////////
1073
+ //@requires: ByteArrayAppend
1074
+
1075
+ static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value) {
1076
+ Py_ssize_t ival;
1077
+ #if PY_MAJOR_VERSION < 3
1078
+ if (unlikely(PyString_Check(value))) {
1079
+ if (unlikely(PyString_GET_SIZE(value) != 1)) {
1080
+ PyErr_SetString(PyExc_ValueError, "string must be of size 1");
1081
+ return -1;
1082
+ }
1083
+ ival = (unsigned char) (PyString_AS_STRING(value)[0]);
1084
+ } else
1085
+ #endif
1086
+ #if CYTHON_USE_PYLONG_INTERNALS
1087
+ if (likely(PyLong_CheckExact(value)) && likely(__Pyx_PyLong_IsCompact(value))) {
1088
+ if (__Pyx_PyLong_IsZero(value)) {
1089
+ ival = 0;
1090
+ } else {
1091
+ ival = __Pyx_PyLong_CompactValue(value);
1092
+ if (unlikely(ival > 255)) goto bad_range;
1093
+ }
1094
+ } else
1095
+ #endif
1096
+ {
1097
+ // CPython calls PyNumber_Index() internally
1098
+ ival = __Pyx_PyIndex_AsSsize_t(value);
1099
+ if (unlikely(!__Pyx_is_valid_index(ival, 256))) {
1100
+ if (ival == -1 && PyErr_Occurred())
1101
+ return -1;
1102
+ goto bad_range;
1103
+ }
1104
+ }
1105
+ return __Pyx_PyByteArray_Append(bytearray, ival);
1106
+ bad_range:
1107
+ PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1108
+ return -1;
1109
+ }
1110
+
1111
+ //////////////////// ByteArrayAppend.proto ////////////////////
1112
+
1113
+ static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value);
1114
+
1115
+ //////////////////// ByteArrayAppend ////////////////////
1116
+ //@requires: ObjectHandling.c::PyObjectCallMethod1
1117
+
1118
+ static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value) {
1119
+ PyObject *pyval, *retval;
1120
+ #if CYTHON_COMPILING_IN_CPYTHON
1121
+ if (likely(__Pyx_is_valid_index(value, 256))) {
1122
+ Py_ssize_t n = Py_SIZE(bytearray);
1123
+ if (likely(n != PY_SSIZE_T_MAX)) {
1124
+ if (unlikely(PyByteArray_Resize(bytearray, n + 1) < 0))
1125
+ return -1;
1126
+ PyByteArray_AS_STRING(bytearray)[n] = value;
1127
+ return 0;
1128
+ }
1129
+ } else {
1130
+ PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1131
+ return -1;
1132
+ }
1133
+ #endif
1134
+ pyval = PyInt_FromLong(value);
1135
+ if (unlikely(!pyval))
1136
+ return -1;
1137
+ retval = __Pyx_PyObject_CallMethod1(bytearray, PYIDENT("append"), pyval);
1138
+ Py_DECREF(pyval);
1139
+ if (unlikely(!retval))
1140
+ return -1;
1141
+ Py_DECREF(retval);
1142
+ return 0;
1143
+ }
1144
+
1145
+
1146
+ //////////////////// PyObjectFormat.proto ////////////////////
1147
+
1148
+ #if CYTHON_USE_UNICODE_WRITER
1149
+ static PyObject* __Pyx_PyObject_Format(PyObject* s, PyObject* f);
1150
+ #else
1151
+ #define __Pyx_PyObject_Format(s, f) PyObject_Format(s, f)
1152
+ #endif
1153
+
1154
+ //////////////////// PyObjectFormat ////////////////////
1155
+
1156
+ #if CYTHON_USE_UNICODE_WRITER
1157
+ static PyObject* __Pyx_PyObject_Format(PyObject* obj, PyObject* format_spec) {
1158
+ int ret;
1159
+ _PyUnicodeWriter writer;
1160
+
1161
+ if (likely(PyFloat_CheckExact(obj))) {
1162
+ // copied from CPython 3.5 "float__format__()" in floatobject.c
1163
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x03040000
1164
+ _PyUnicodeWriter_Init(&writer, 0);
1165
+ #else
1166
+ _PyUnicodeWriter_Init(&writer);
1167
+ #endif
1168
+ ret = _PyFloat_FormatAdvancedWriter(
1169
+ &writer,
1170
+ obj,
1171
+ format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1172
+ } else if (likely(PyLong_CheckExact(obj))) {
1173
+ // copied from CPython 3.5 "long__format__()" in longobject.c
1174
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x03040000
1175
+ _PyUnicodeWriter_Init(&writer, 0);
1176
+ #else
1177
+ _PyUnicodeWriter_Init(&writer);
1178
+ #endif
1179
+ ret = _PyLong_FormatAdvancedWriter(
1180
+ &writer,
1181
+ obj,
1182
+ format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
1183
+ } else {
1184
+ return PyObject_Format(obj, format_spec);
1185
+ }
1186
+
1187
+ if (unlikely(ret == -1)) {
1188
+ _PyUnicodeWriter_Dealloc(&writer);
1189
+ return NULL;
1190
+ }
1191
+ return _PyUnicodeWriter_Finish(&writer);
1192
+ }
1193
+ #endif
1194
+
1195
+
1196
+ //////////////////// PyObjectFormatSimple.proto ////////////////////
1197
+
1198
+ #if CYTHON_COMPILING_IN_PYPY
1199
+ #define __Pyx_PyObject_FormatSimple(s, f) ( \
1200
+ likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) : \
1201
+ PyObject_Format(s, f))
1202
+ #elif PY_MAJOR_VERSION < 3
1203
+ // str is common in Py2, but formatting must return a Unicode string
1204
+ #define __Pyx_PyObject_FormatSimple(s, f) ( \
1205
+ likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) : \
1206
+ likely(PyString_CheckExact(s)) ? PyUnicode_FromEncodedObject(s, NULL, "strict") : \
1207
+ PyObject_Format(s, f))
1208
+ #elif CYTHON_USE_TYPE_SLOTS
1209
+ // Py3 nicely returns unicode strings from str() and repr(), which makes this quite efficient for builtin types.
1210
+ // In Py3.8+, tp_str() delegates to tp_repr(), so we call tp_repr() directly here.
1211
+ #define __Pyx_PyObject_FormatSimple(s, f) ( \
1212
+ likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) : \
1213
+ likely(PyLong_CheckExact(s)) ? PyLong_Type.tp_repr(s) : \
1214
+ likely(PyFloat_CheckExact(s)) ? PyFloat_Type.tp_repr(s) : \
1215
+ PyObject_Format(s, f))
1216
+ #else
1217
+ #define __Pyx_PyObject_FormatSimple(s, f) ( \
1218
+ likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) : \
1219
+ PyObject_Format(s, f))
1220
+ #endif
1221
+
1222
+
1223
+ //////////////////// PyObjectFormatAndDecref.proto ////////////////////
1224
+
1225
+ static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f);
1226
+ static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f);
1227
+
1228
+ //////////////////// PyObjectFormatAndDecref ////////////////////
1229
+
1230
+ static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f) {
1231
+ if (unlikely(!s)) return NULL;
1232
+ if (likely(PyUnicode_CheckExact(s))) return s;
1233
+ #if PY_MAJOR_VERSION < 3
1234
+ // str is common in Py2, but formatting must return a Unicode string
1235
+ if (likely(PyString_CheckExact(s))) {
1236
+ PyObject *result = PyUnicode_FromEncodedObject(s, NULL, "strict");
1237
+ Py_DECREF(s);
1238
+ return result;
1239
+ }
1240
+ #endif
1241
+ return __Pyx_PyObject_FormatAndDecref(s, f);
1242
+ }
1243
+
1244
+ static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f) {
1245
+ PyObject *result;
1246
+ if (unlikely(!s)) return NULL;
1247
+ result = PyObject_Format(s, f);
1248
+ Py_DECREF(s);
1249
+ return result;
1250
+ }
1251
+
1252
+
1253
+ //////////////////// PyUnicode_Unicode.proto ////////////////////
1254
+
1255
+ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Unicode(PyObject *obj);/*proto*/
1256
+
1257
+ //////////////////// PyUnicode_Unicode ////////////////////
1258
+
1259
+ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Unicode(PyObject *obj) {
1260
+ if (unlikely(obj == Py_None))
1261
+ obj = PYUNICODE("None");
1262
+ return __Pyx_NewRef(obj);
1263
+ }
1264
+
1265
+
1266
+ //////////////////// PyObject_Unicode.proto ////////////////////
1267
+
1268
+ #if PY_MAJOR_VERSION >= 3
1269
+ #define __Pyx_PyObject_Unicode(obj) \
1270
+ (likely(PyUnicode_CheckExact(obj)) ? __Pyx_NewRef(obj) : PyObject_Str(obj))
1271
+ #else
1272
+ #define __Pyx_PyObject_Unicode(obj) \
1273
+ (likely(PyUnicode_CheckExact(obj)) ? __Pyx_NewRef(obj) : PyObject_Unicode(obj))
1274
+ #endif
1275
+
1276
+
1277
+ //////////////////// PyStr_Str.proto ////////////////////
1278
+
1279
+ static CYTHON_INLINE PyObject* __Pyx_PyStr_Str(PyObject *obj);/*proto*/
1280
+
1281
+ //////////////////// PyStr_Str ////////////////////
1282
+
1283
+ static CYTHON_INLINE PyObject* __Pyx_PyStr_Str(PyObject *obj) {
1284
+ if (unlikely(obj == Py_None))
1285
+ obj = PYIDENT("None");
1286
+ return __Pyx_NewRef(obj);
1287
+ }
1288
+
1289
+
1290
+ //////////////////// PyObject_Str.proto ////////////////////
1291
+
1292
+ #define __Pyx_PyObject_Str(obj) \
1293
+ (likely(PyString_CheckExact(obj)) ? __Pyx_NewRef(obj) : PyObject_Str(obj))
1294
+
tuning-competition-baseline/.venv/lib/python3.11/site-packages/Cython/Utility/UFuncs_C.c ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ///////////////////////// UFuncsInit.proto /////////////////////////
2
+ //@proto_block: utility_code_proto_before_types
3
+
4
+ #include <numpy/arrayobject.h>
5
+ #include <numpy/ufuncobject.h>
6
+
7
+ // account for change in type of arguments to PyUFuncGenericFunction in Numpy 1.19.x
8
+ // Unfortunately we can only test against Numpy version 1.20.x since it wasn't marked
9
+ // as an API break. Therefore, I'm "solving" the issue by casting function pointer types
10
+ // on lower Numpy versions.
11
+ #if NPY_API_VERSION >= 0x0000000e // Numpy 1.20.x
12
+ #define __PYX_PYUFUNCGENERICFUNCTION_CAST(x) x
13
+ #else
14
+ #define __PYX_PYUFUNCGENERICFUNCTION_CAST(x) (PyUFuncGenericFunction)x
15
+ #endif
16
+
17
+ /////////////////////// UFuncConsts.proto ////////////////////
18
+
19
+ // getter functions because we can't forward-declare arrays
20
+ static PyUFuncGenericFunction* {{ufunc_funcs_name}}(void); /* proto */
21
+ static char* {{ufunc_types_name}}(void); /* proto */
22
+ static void* {{ufunc_data_name}}[] = {NULL}; /* always null */
23
+
24
+ /////////////////////// UFuncConsts /////////////////////////
25
+
26
+ static PyUFuncGenericFunction* {{ufunc_funcs_name}}(void) {
27
+ static PyUFuncGenericFunction arr[] = {
28
+ {{for loop, cname in looper(func_cnames)}}
29
+ __PYX_PYUFUNCGENERICFUNCTION_CAST(&{{cname}}){{if not loop.last}},{{endif}}
30
+ {{endfor}}
31
+ };
32
+ return arr;
33
+ }
34
+
35
+ static char* {{ufunc_types_name}}(void) {
36
+ static char arr[] = {
37
+ {{for loop, tp in looper(type_constants)}}
38
+ {{tp}}{{if not loop.last}},{{endif}}
39
+ {{endfor}}
40
+ };
41
+ return arr;
42
+ }
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.55 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc ADDED
Binary file (50.6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_centrality.cpython-311.pyc ADDED
Binary file (8.73 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-311.pyc ADDED
Binary file (3.04 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-311.pyc ADDED
Binary file (7.65 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_generators.cpython-311.pyc ADDED
Binary file (23.9 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matching.cpython-311.pyc ADDED
Binary file (23.6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matrix.cpython-311.pyc ADDED
Binary file (8.12 kB). View file