oxython 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. Cython/Build/BuildExecutable.py +156 -0
  2. Cython/Build/Cache.py +198 -0
  3. Cython/Build/Cythonize.py +349 -0
  4. Cython/Build/Dependencies.py +1320 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +467 -0
  7. Cython/Build/IpythonMagic.py +559 -0
  8. Cython/Build/SharedModule.py +165 -0
  9. Cython/Build/Tests/TestCyCache.py +222 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +480 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +303 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +825 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +679 -0
  23. Cython/Compiler/Builtin.py +1102 -0
  24. Cython/Compiler/CmdLine.py +373 -0
  25. Cython/Compiler/Code.pxd +154 -0
  26. Cython/Compiler/Code.py +3760 -0
  27. Cython/Compiler/CodeGeneration.py +33 -0
  28. Cython/Compiler/CythonScope.py +208 -0
  29. Cython/Compiler/Dataclass.py +890 -0
  30. Cython/Compiler/DebugFlags.py +24 -0
  31. Cython/Compiler/Errors.py +310 -0
  32. Cython/Compiler/ExprNodes.py +16319 -0
  33. Cython/Compiler/FlowControl.pxd +112 -0
  34. Cython/Compiler/FlowControl.py +1575 -0
  35. Cython/Compiler/FusedNode.py +978 -0
  36. Cython/Compiler/Future.py +16 -0
  37. Cython/Compiler/Interpreter.py +57 -0
  38. Cython/Compiler/Lexicon.py +442 -0
  39. Cython/Compiler/LineTable.py +114 -0
  40. Cython/Compiler/Main.py +879 -0
  41. Cython/Compiler/MatchCaseNodes.py +2200 -0
  42. Cython/Compiler/MemoryView.py +930 -0
  43. Cython/Compiler/ModuleNode.py +4558 -0
  44. Cython/Compiler/Naming.py +370 -0
  45. Cython/Compiler/Nodes.py +11334 -0
  46. Cython/Compiler/Optimize.py +5563 -0
  47. Cython/Compiler/Options.py +841 -0
  48. Cython/Compiler/ParseTreeTransforms.pxd +80 -0
  49. Cython/Compiler/ParseTreeTransforms.py +4808 -0
  50. Cython/Compiler/Parsing.pxd +9 -0
  51. Cython/Compiler/Parsing.py +5442 -0
  52. Cython/Compiler/Pipeline.py +439 -0
  53. Cython/Compiler/PyrexTypes.py +6588 -0
  54. Cython/Compiler/Pythran.py +232 -0
  55. Cython/Compiler/Scanning.pxd +74 -0
  56. Cython/Compiler/Scanning.py +771 -0
  57. Cython/Compiler/StringEncoding.py +354 -0
  58. Cython/Compiler/Symtab.py +3122 -0
  59. Cython/Compiler/Tests/TestBuffer.py +105 -0
  60. Cython/Compiler/Tests/TestBuiltin.py +196 -0
  61. Cython/Compiler/Tests/TestCmdLine.py +652 -0
  62. Cython/Compiler/Tests/TestCode.py +145 -0
  63. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  64. Cython/Compiler/Tests/TestGrammar.py +202 -0
  65. Cython/Compiler/Tests/TestMemView.py +71 -0
  66. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  67. Cython/Compiler/Tests/TestScanning.py +132 -0
  68. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  69. Cython/Compiler/Tests/TestStringEncoding.py +20 -0
  70. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  71. Cython/Compiler/Tests/TestTreePath.py +103 -0
  72. Cython/Compiler/Tests/TestTypes.py +119 -0
  73. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  74. Cython/Compiler/Tests/TestVisitor.py +119 -0
  75. Cython/Compiler/Tests/Utils.py +36 -0
  76. Cython/Compiler/Tests/__init__.py +1 -0
  77. Cython/Compiler/TreeFragment.py +279 -0
  78. Cython/Compiler/TreePath.py +303 -0
  79. Cython/Compiler/TypeInference.py +626 -0
  80. Cython/Compiler/TypeSlots.py +1330 -0
  81. Cython/Compiler/UFuncs.py +317 -0
  82. Cython/Compiler/UtilNodes.py +389 -0
  83. Cython/Compiler/UtilityCode.py +354 -0
  84. Cython/Compiler/Version.py +8 -0
  85. Cython/Compiler/Visitor.pxd +52 -0
  86. Cython/Compiler/Visitor.py +914 -0
  87. Cython/Compiler/__init__.py +1 -0
  88. Cython/Coverage.py +448 -0
  89. Cython/Debugger/Cygdb.py +214 -0
  90. Cython/Debugger/DebugWriter.py +82 -0
  91. Cython/Debugger/Tests/TestLibCython.py +280 -0
  92. Cython/Debugger/Tests/__init__.py +1 -0
  93. Cython/Debugger/Tests/cfuncs.c +8 -0
  94. Cython/Debugger/Tests/codefile +49 -0
  95. Cython/Debugger/Tests/test_libcython_in_gdb.py +580 -0
  96. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  97. Cython/Debugger/__init__.py +1 -0
  98. Cython/Debugger/libcython.py +1548 -0
  99. Cython/Debugger/libpython.py +2821 -0
  100. Cython/Debugging.py +20 -0
  101. Cython/Distutils/__init__.py +2 -0
  102. Cython/Distutils/build_ext.py +143 -0
  103. Cython/Distutils/extension.py +96 -0
  104. Cython/Distutils/old_build_ext.py +351 -0
  105. Cython/Includes/cpython/__init__.pxd +173 -0
  106. Cython/Includes/cpython/array.pxd +159 -0
  107. Cython/Includes/cpython/bool.pxd +37 -0
  108. Cython/Includes/cpython/buffer.pxd +112 -0
  109. Cython/Includes/cpython/bytearray.pxd +33 -0
  110. Cython/Includes/cpython/bytes.pxd +200 -0
  111. Cython/Includes/cpython/cellobject.pxd +35 -0
  112. Cython/Includes/cpython/ceval.pxd +8 -0
  113. Cython/Includes/cpython/codecs.pxd +121 -0
  114. Cython/Includes/cpython/complex.pxd +60 -0
  115. Cython/Includes/cpython/contextvars.pxd +145 -0
  116. Cython/Includes/cpython/conversion.pxd +36 -0
  117. Cython/Includes/cpython/datetime.pxd +395 -0
  118. Cython/Includes/cpython/descr.pxd +26 -0
  119. Cython/Includes/cpython/dict.pxd +268 -0
  120. Cython/Includes/cpython/exc.pxd +263 -0
  121. Cython/Includes/cpython/fileobject.pxd +57 -0
  122. Cython/Includes/cpython/float.pxd +56 -0
  123. Cython/Includes/cpython/frozendict.pxd +37 -0
  124. Cython/Includes/cpython/function.pxd +65 -0
  125. Cython/Includes/cpython/genobject.pxd +25 -0
  126. Cython/Includes/cpython/getargs.pxd +12 -0
  127. Cython/Includes/cpython/instance.pxd +25 -0
  128. Cython/Includes/cpython/iterator.pxd +36 -0
  129. Cython/Includes/cpython/iterobject.pxd +24 -0
  130. Cython/Includes/cpython/list.pxd +144 -0
  131. Cython/Includes/cpython/long.pxd +180 -0
  132. Cython/Includes/cpython/longintrepr.pxd +14 -0
  133. Cython/Includes/cpython/mapping.pxd +63 -0
  134. Cython/Includes/cpython/marshal.pxd +66 -0
  135. Cython/Includes/cpython/mem.pxd +120 -0
  136. Cython/Includes/cpython/memoryview.pxd +50 -0
  137. Cython/Includes/cpython/method.pxd +49 -0
  138. Cython/Includes/cpython/module.pxd +208 -0
  139. Cython/Includes/cpython/number.pxd +258 -0
  140. Cython/Includes/cpython/object.pxd +430 -0
  141. Cython/Includes/cpython/pycapsule.pxd +143 -0
  142. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  143. Cython/Includes/cpython/pyport.pxd +8 -0
  144. Cython/Includes/cpython/pystate.pxd +95 -0
  145. Cython/Includes/cpython/pythread.pxd +53 -0
  146. Cython/Includes/cpython/ref.pxd +141 -0
  147. Cython/Includes/cpython/sentinel.pxd +17 -0
  148. Cython/Includes/cpython/sequence.pxd +134 -0
  149. Cython/Includes/cpython/set.pxd +119 -0
  150. Cython/Includes/cpython/slice.pxd +70 -0
  151. Cython/Includes/cpython/time.pxd +129 -0
  152. Cython/Includes/cpython/tuple.pxd +72 -0
  153. Cython/Includes/cpython/type.pxd +146 -0
  154. Cython/Includes/cpython/unicode.pxd +639 -0
  155. Cython/Includes/cpython/version.pxd +32 -0
  156. Cython/Includes/cpython/weakref.pxd +78 -0
  157. Cython/Includes/libc/__init__.pxd +1 -0
  158. Cython/Includes/libc/complex.pxd +35 -0
  159. Cython/Includes/libc/errno.pxd +127 -0
  160. Cython/Includes/libc/float.pxd +43 -0
  161. Cython/Includes/libc/limits.pxd +28 -0
  162. Cython/Includes/libc/locale.pxd +46 -0
  163. Cython/Includes/libc/math.pxd +209 -0
  164. Cython/Includes/libc/setjmp.pxd +10 -0
  165. Cython/Includes/libc/signal.pxd +64 -0
  166. Cython/Includes/libc/stdbool.pxd +5 -0
  167. Cython/Includes/libc/stddef.pxd +9 -0
  168. Cython/Includes/libc/stdint.pxd +105 -0
  169. Cython/Includes/libc/stdio.pxd +80 -0
  170. Cython/Includes/libc/stdlib.pxd +72 -0
  171. Cython/Includes/libc/string.pxd +50 -0
  172. Cython/Includes/libc/threads.pxd +234 -0
  173. Cython/Includes/libc/time.pxd +52 -0
  174. Cython/Includes/libcpp/__init__.pxd +4 -0
  175. Cython/Includes/libcpp/algorithm.pxd +320 -0
  176. Cython/Includes/libcpp/any.pxd +16 -0
  177. Cython/Includes/libcpp/atomic.pxd +59 -0
  178. Cython/Includes/libcpp/barrier.pxd +22 -0
  179. Cython/Includes/libcpp/bit.pxd +29 -0
  180. Cython/Includes/libcpp/cast.pxd +12 -0
  181. Cython/Includes/libcpp/cmath.pxd +518 -0
  182. Cython/Includes/libcpp/complex.pxd +106 -0
  183. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  184. Cython/Includes/libcpp/deque.pxd +165 -0
  185. Cython/Includes/libcpp/exception.pxd +216 -0
  186. Cython/Includes/libcpp/execution.pxd +15 -0
  187. Cython/Includes/libcpp/forward_list.pxd +63 -0
  188. Cython/Includes/libcpp/functional.pxd +26 -0
  189. Cython/Includes/libcpp/future.pxd +103 -0
  190. Cython/Includes/libcpp/iterator.pxd +34 -0
  191. Cython/Includes/libcpp/latch.pxd +17 -0
  192. Cython/Includes/libcpp/limits.pxd +61 -0
  193. Cython/Includes/libcpp/list.pxd +117 -0
  194. Cython/Includes/libcpp/map.pxd +252 -0
  195. Cython/Includes/libcpp/memory.pxd +115 -0
  196. Cython/Includes/libcpp/mutex.pxd +387 -0
  197. Cython/Includes/libcpp/numbers.pxd +15 -0
  198. Cython/Includes/libcpp/numeric.pxd +131 -0
  199. Cython/Includes/libcpp/optional.pxd +34 -0
  200. Cython/Includes/libcpp/pair.pxd +1 -0
  201. Cython/Includes/libcpp/queue.pxd +25 -0
  202. Cython/Includes/libcpp/random.pxd +166 -0
  203. Cython/Includes/libcpp/semaphore.pxd +43 -0
  204. Cython/Includes/libcpp/set.pxd +228 -0
  205. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  206. Cython/Includes/libcpp/span.pxd +87 -0
  207. Cython/Includes/libcpp/stack.pxd +11 -0
  208. Cython/Includes/libcpp/stop_token.pxd +117 -0
  209. Cython/Includes/libcpp/string.pxd +355 -0
  210. Cython/Includes/libcpp/string_view.pxd +183 -0
  211. Cython/Includes/libcpp/typeindex.pxd +15 -0
  212. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  213. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  214. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  215. Cython/Includes/libcpp/utility.pxd +30 -0
  216. Cython/Includes/libcpp/vector.pxd +186 -0
  217. Cython/Includes/numpy/math.pxd +150 -0
  218. Cython/Includes/openmp.pxd +50 -0
  219. Cython/Includes/posix/__init__.pxd +1 -0
  220. Cython/Includes/posix/dlfcn.pxd +14 -0
  221. Cython/Includes/posix/fcntl.pxd +86 -0
  222. Cython/Includes/posix/ioctl.pxd +4 -0
  223. Cython/Includes/posix/mman.pxd +101 -0
  224. Cython/Includes/posix/resource.pxd +57 -0
  225. Cython/Includes/posix/select.pxd +21 -0
  226. Cython/Includes/posix/signal.pxd +73 -0
  227. Cython/Includes/posix/stat.pxd +98 -0
  228. Cython/Includes/posix/stdio.pxd +37 -0
  229. Cython/Includes/posix/stdlib.pxd +29 -0
  230. Cython/Includes/posix/strings.pxd +9 -0
  231. Cython/Includes/posix/time.pxd +71 -0
  232. Cython/Includes/posix/types.pxd +30 -0
  233. Cython/Includes/posix/uio.pxd +26 -0
  234. Cython/Includes/posix/unistd.pxd +271 -0
  235. Cython/Includes/posix/wait.pxd +38 -0
  236. Cython/LZSS.py +184 -0
  237. Cython/Plex/Actions.pxd +24 -0
  238. Cython/Plex/Actions.py +119 -0
  239. Cython/Plex/DFA.pxd +14 -0
  240. Cython/Plex/DFA.py +164 -0
  241. Cython/Plex/Errors.py +48 -0
  242. Cython/Plex/Lexicons.py +178 -0
  243. Cython/Plex/Machines.pxd +36 -0
  244. Cython/Plex/Machines.py +238 -0
  245. Cython/Plex/Regexps.py +535 -0
  246. Cython/Plex/Scanners.pxd +45 -0
  247. Cython/Plex/Scanners.py +328 -0
  248. Cython/Plex/Transitions.pxd +14 -0
  249. Cython/Plex/Transitions.py +239 -0
  250. Cython/Plex/__init__.py +34 -0
  251. Cython/Runtime/__init__.py +1 -0
  252. Cython/Runtime/refnanny.pyx +237 -0
  253. Cython/Shadow.py +1172 -0
  254. Cython/StringIOTree.py +169 -0
  255. Cython/Tempita/__init__.py +4 -0
  256. Cython/Tempita/_looper.py +154 -0
  257. Cython/Tempita/_tempita.py +1087 -0
  258. Cython/TestUtils.py +472 -0
  259. Cython/Tests/TestCodeWriter.py +128 -0
  260. Cython/Tests/TestCythonUtils.py +237 -0
  261. Cython/Tests/TestJediTyper.py +223 -0
  262. Cython/Tests/TestShadow.py +125 -0
  263. Cython/Tests/TestStringIOTree.py +68 -0
  264. Cython/Tests/TestTestUtils.py +89 -0
  265. Cython/Tests/__init__.py +1 -0
  266. Cython/Tests/xmlrunner.py +390 -0
  267. Cython/Utility/AsyncGen.c +1152 -0
  268. Cython/Utility/Buffer.c +866 -0
  269. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  270. Cython/Utility/Builtins.c +1068 -0
  271. Cython/Utility/CConvert.pyx +153 -0
  272. Cython/Utility/CMath.c +104 -0
  273. Cython/Utility/CommonStructures.c +244 -0
  274. Cython/Utility/Complex.c +378 -0
  275. Cython/Utility/Coroutine.c +2344 -0
  276. Cython/Utility/CpdefEnums.pyx +119 -0
  277. Cython/Utility/CppConvert.pyx +284 -0
  278. Cython/Utility/CppSupport.cpp +151 -0
  279. Cython/Utility/CythonFunction.c +2143 -0
  280. Cython/Utility/Dataclasses.c +101 -0
  281. Cython/Utility/Embed.c +129 -0
  282. Cython/Utility/Exceptions.c +1331 -0
  283. Cython/Utility/Exceptions_Cy.pyx +109 -0
  284. Cython/Utility/ExtensionTypes.c +1199 -0
  285. Cython/Utility/FunctionArguments.c +1052 -0
  286. Cython/Utility/FusedFunction.pyx +44 -0
  287. Cython/Utility/ImportExport.c +972 -0
  288. Cython/Utility/MatchCase.c +985 -0
  289. Cython/Utility/MatchCase_Cy.pyx +12 -0
  290. Cython/Utility/MemoryView.pxd +108 -0
  291. Cython/Utility/MemoryView.pyx +1499 -0
  292. Cython/Utility/MemoryView_C.c +1056 -0
  293. Cython/Utility/ModuleSetupCode.c +3349 -0
  294. Cython/Utility/NumpyImportArray.c +46 -0
  295. Cython/Utility/ObjectHandling.c +3404 -0
  296. Cython/Utility/Optimize.c +2575 -0
  297. Cython/Utility/Overflow.c +378 -0
  298. Cython/Utility/Profile.c +736 -0
  299. Cython/Utility/StringTools.c +1534 -0
  300. Cython/Utility/Synchronization.c +438 -0
  301. Cython/Utility/TString.c +369 -0
  302. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  303. Cython/Utility/TestCythonScope.pyx +75 -0
  304. Cython/Utility/TestUtilityLoader.c +12 -0
  305. Cython/Utility/TypeConversion.c +1588 -0
  306. Cython/Utility/UFuncs.pyx +50 -0
  307. Cython/Utility/UFuncs_C.c +89 -0
  308. Cython/Utility/__init__.py +28 -0
  309. Cython/Utility/arrayarray.h +190 -0
  310. Cython/Utils.py +682 -0
  311. Cython/__init__.py +12 -0
  312. Cython/py.typed +0 -0
  313. cython.py +29 -0
  314. oxython-0.1.0.dist-info/METADATA +138 -0
  315. oxython-0.1.0.dist-info/RECORD +321 -0
  316. oxython-0.1.0.dist-info/WHEEL +5 -0
  317. oxython-0.1.0.dist-info/entry_points.txt +4 -0
  318. oxython-0.1.0.dist-info/top_level.txt +3 -0
  319. pyximport/__init__.py +4 -0
  320. pyximport/pyxbuild.py +160 -0
  321. pyximport/pyximport.py +482 -0
@@ -0,0 +1,3122 @@
1
+ #
2
+ # Symbol Table
3
+ #
4
+
5
+ # uses @try_finally_contextmanager
6
+ # cython: binding=True
7
+
8
+ import re
9
+ import copy
10
+ import operator
11
+
12
+ from ..Utils import try_finally_contextmanager
13
+ from .Errors import warning, error, InternalError, performance_hint
14
+ from .StringEncoding import EncodedString
15
+ from . import Options, Naming
16
+ from . import PyrexTypes
17
+ from .PyrexTypes import py_object_type, unspecified_type
18
+ from .TypeSlots import (
19
+ pyfunction_signature, pymethod_signature, richcmp_special_methods,
20
+ get_slot_table, get_property_accessor_signature)
21
+ from . import DebugFlags
22
+
23
+ from . import Code
24
+
25
+
26
+ def c_safe_identifier(cname):
27
+ # There are some C limitations on struct entry names.
28
+ if ((cname[:2] == '__' and not (cname.startswith(Naming.pyrex_prefix)
29
+ or cname in ('__weakref__', '__dict__')))
30
+ or cname in Naming.reserved_cnames):
31
+ cname = Naming.pyrex_prefix + cname
32
+ return cname
33
+
34
+
35
+ def punycodify_name(cname, mangle_with=None):
36
+ # if passed the mangle_with should be a byte string
37
+ # modified from PEP489
38
+ if cname.isascii():
39
+ return cname
40
+
41
+ cname = cname.encode('punycode').replace(b'-', b'_').decode('ascii')
42
+ if mangle_with:
43
+ # sometimes it necessary to mangle unicode names alone where
44
+ # they'll be inserted directly into C, because the punycode
45
+ # transformation can turn them into invalid identifiers
46
+ cname = "%s_%s" % (mangle_with, cname)
47
+ elif cname.startswith(Naming.pyrex_prefix):
48
+ # a punycode name could also be a valid ascii variable name so
49
+ # change the prefix to distinguish
50
+ cname = cname.replace(Naming.pyrex_prefix,
51
+ Naming.pyunicode_identifier_prefix, 1)
52
+
53
+ return cname
54
+
55
+
56
+ class BufferAux:
57
+ writable_needed = False
58
+
59
+ def __init__(self, buflocal_nd_var, rcbuf_var):
60
+ self.buflocal_nd_var = buflocal_nd_var
61
+ self.rcbuf_var = rcbuf_var
62
+
63
+ def __repr__(self):
64
+ return "<BufferAux %r>" % self.__dict__
65
+
66
+
67
+ class Entry:
68
+ # A symbol table entry in a Scope or ModuleNamespace.
69
+ #
70
+ # name string Python name of entity
71
+ # cname string C name of entity
72
+ # type PyrexType Type of entity
73
+ # doc string Doc string
74
+ # annotation ExprNode PEP 484/526 annotation
75
+ # init string Initial value
76
+ # visibility 'private' or 'public' or 'extern'
77
+ # is_builtin boolean Is an entry in the Python builtins dict
78
+ # is_cglobal boolean Is a C global variable
79
+ # is_pyglobal boolean Is a Python module-level variable
80
+ # or class attribute during
81
+ # class construction
82
+ # is_member boolean Is an assigned class member
83
+ # is_pyclass_attr boolean Is a name in a Python class namespace
84
+ # is_variable boolean Is a variable
85
+ # is_cfunction boolean Is a C function
86
+ # is_cmethod boolean Is a C method of an extension type
87
+ # is_builtin_cmethod boolean Is a C method of a builtin type (implies is_cmethod)
88
+ # is_unbound_cmethod boolean Is an unbound C method of an extension type
89
+ # is_final_cmethod boolean Is non-overridable C method
90
+ # is_inline_cmethod boolean Is inlined C method
91
+ # is_anonymous boolean Is a anonymous pyfunction entry
92
+ # is_type boolean Is a type definition
93
+ # is_cclass boolean Is an extension class
94
+ # is_cclass_var_rentry boolean Is a var entry of an extension type
95
+ # (Hack! Only needed because most C globals are
96
+ # static variables while these live in the module scope.
97
+ # Remove when fixed.)
98
+ # is_cpp_class boolean Is a C++ class
99
+ # is_const boolean Is a constant
100
+ # is_property boolean Is a property of an extension type:
101
+ # doc_cname string or None C const holding the docstring
102
+ # getter_cname string C func for getting property
103
+ # setter_cname string C func for setting or deleting property
104
+ # is_cproperty boolean Is an inline property of an external type
105
+ # is_self_arg boolean Is the "self" arg of an exttype method
106
+ # is_arg boolean Is the arg of a method
107
+ # is_local boolean Is a local variable
108
+ # in_closure boolean Is referenced in an inner scope
109
+ # in_subscope boolean Belongs to a generator expression scope
110
+ # is_readonly boolean Can't be assigned to
111
+ # func_cname string C func implementing Python func
112
+ # wrapperbase_cname [string] C wrapperbase object name
113
+ # func_modifiers [string] C function modifiers ('inline')
114
+ # pos position Source position where declared
115
+ # namespace_cname string If is_pyglobal, the C variable
116
+ # holding its home namespace
117
+ # pymethdef_cname string PyMethodDef structure
118
+ # signature Signature Arg & return types for Python func
119
+ # as_variable Entry Alternative interpretation of extension
120
+ # type name or builtin C function as a variable
121
+ # xdecref_cleanup boolean Use Py_XDECREF for error cleanup
122
+ # in_cinclude boolean Suppress C declaration code
123
+ # enum_values [Entry] For enum types, list of values
124
+ # qualified_name string "modname.funcname" or "modname.classname"
125
+ # or "modname.classname.funcname"
126
+ # is_declared_generic boolean Is declared as PyObject * even though its
127
+ # type is an extension type
128
+ # as_module None Module scope, if a cimported module
129
+ # is_inherited boolean Is an inherited attribute of an extension type
130
+ # pystring_cname string C name of Python version of string literal
131
+ # is_interned boolean For string const entries, value is interned
132
+ # is_identifier boolean For string const entries, value is an identifier
133
+ # used boolean
134
+ # is_special boolean Is a special method or property accessor
135
+ # of an extension type
136
+ # defined_in_pxd boolean Is defined in a .pxd file (not just declared)
137
+ # api boolean Generate C API for C class or function
138
+ # utility_code string Utility code needed when this entry is used
139
+ #
140
+ # buffer_aux BufferAux or None Extra information needed for buffer variables
141
+ # inline_func_in_pxd boolean Hacky special case for inline function in pxd file.
142
+ # Ideally this should not be necessary.
143
+ # might_overflow boolean In an arithmetic expression that could cause
144
+ # overflow (used for type inference).
145
+ # utility_code_definition For some Cython builtins, the utility code
146
+ # which contains the definition of the entry.
147
+ # Currently only supported for CythonScope entries.
148
+ # error_on_uninitialized Have Control Flow issue an error when this entry is
149
+ # used uninitialized
150
+ # cf_used boolean Entry is used
151
+ # is_fused_specialized boolean Whether this entry of a cdef or def function
152
+ # is a specialization
153
+ # is_cgetter boolean Is a c-level getter function
154
+ # is_cpp_optional boolean Entry should be declared as std::optional (cpp_locals directive)
155
+ # known_standard_library_import Either None (default), an empty string (definitely can't be determined)
156
+ # or a string of "modulename.something.attribute"
157
+ # Used for identifying imports from typing/dataclasses etc
158
+ # pytyping_modifiers Python type modifiers like "typing.ClassVar" but also "dataclasses.InitVar"
159
+ # enum_int_value None or int If known, the int that corresponds to this enum value
160
+ # specialiser function or None Callable to specialise a function to specific C arguments.
161
+
162
+ # TODO: utility_code and utility_code_definition serves the same purpose...
163
+
164
+ inline_func_in_pxd = False
165
+ borrowed = 0
166
+ init = ""
167
+ annotation = None
168
+ visibility = 'private'
169
+ is_builtin = 0
170
+ is_cglobal = 0
171
+ is_pyglobal = 0
172
+ is_member = 0
173
+ is_pyclass_attr = 0
174
+ is_variable = 0
175
+ is_cfunction = 0
176
+ is_cmethod = 0
177
+ is_builtin_cmethod = False
178
+ is_unbound_cmethod = 0
179
+ is_final_cmethod = 0
180
+ is_inline_cmethod = 0
181
+ is_anonymous = 0
182
+ is_type = 0
183
+ is_cclass = 0
184
+ is_cclass_var_entry = False # Remove when other cglobals are in the module scope
185
+ is_cpp_class = 0
186
+ is_const = 0
187
+ is_property = 0
188
+ is_cproperty = 0
189
+ doc_cname = None
190
+ getter_cname = None
191
+ setter_cname = None
192
+ is_self_arg = 0
193
+ is_arg = 0
194
+ is_local = 0
195
+ in_closure = 0
196
+ from_closure = 0
197
+ in_subscope = 0
198
+ is_declared_generic = 0
199
+ is_readonly = 0
200
+ pyfunc_cname = None
201
+ func_cname = None
202
+ func_modifiers = []
203
+ final_func_cname = None
204
+ doc = None
205
+ as_variable = None
206
+ xdecref_cleanup = 0
207
+ in_cinclude = 0
208
+ as_module = None
209
+ is_inherited = 0
210
+ pystring_cname = None
211
+ is_identifier = 0
212
+ is_interned = 0
213
+ used = 0
214
+ is_special = 0
215
+ defined_in_pxd = 0
216
+ is_implemented = 0
217
+ api = 0
218
+ utility_code = None
219
+ specialiser = None
220
+ is_overridable = 0
221
+ buffer_aux = None
222
+ prev_entry = None
223
+ might_overflow = 0
224
+ is_auto_typed = False # oxython 'let auto': always infer the C type
225
+ fused_cfunction = None
226
+ is_fused_specialized = False
227
+ utility_code_definition = None
228
+ needs_property = False
229
+ in_with_gil_block = 0
230
+ from_cython_utility_code = None
231
+ error_on_uninitialized = False
232
+ cf_used = True
233
+ outer_entry = None
234
+ is_cgetter = False
235
+ is_cpp_optional = False
236
+ known_standard_library_import = None
237
+ pytyping_modifiers = None
238
+ enum_int_value = None
239
+ vtable_type = None
240
+
241
+ def __init__(self, name, cname, type, pos = None, init = None):
242
+ self.name = name
243
+ self.cname = cname
244
+ self.type = type
245
+ self.pos = pos
246
+ self.init = init
247
+ self.overloaded_alternatives = []
248
+ self.cf_assignments = []
249
+ self.cf_references = []
250
+ self.inner_entries = []
251
+ self.defining_entry = self
252
+
253
+ # Debug helper to find places where entry types are assigned.
254
+ if DebugFlags.debug_verbose_entry_types:
255
+ @property
256
+ def type(self):
257
+ return self.__dict__['type']
258
+
259
+ @type.setter
260
+ def type(self, new_type):
261
+ print(f"ENTRY {self.name}[{self.cname}] TYPE: {self.__dict__.get('type')} -> {new_type}")
262
+ self.__dict__['type'] = new_type
263
+
264
+ def __repr__(self):
265
+ return "%s(<%x>, name=%s, type=%s)" % (type(self).__name__, id(self), self.name, self.type)
266
+
267
+ def already_declared_here(self):
268
+ error(self.pos, "Previous declaration is here")
269
+
270
+ def redeclared(self, pos):
271
+ error(pos, "'%s' does not match previous declaration" % self.name)
272
+ self.already_declared_here()
273
+
274
+ def all_alternatives(self):
275
+ return [self] + self.overloaded_alternatives
276
+
277
+ def best_function_match(self, scope, arg_types, fail_if_empty=False, arg_is_lvalue_array=None):
278
+ func_entry = None
279
+ if self.specialiser is not None:
280
+ func_entry = self.specialiser(scope, arg_types)
281
+ if func_entry is None:
282
+ if self.type.is_fused:
283
+ functypes = self.type.get_all_specialized_function_types()
284
+ alternatives = [f.entry for f in functypes]
285
+ else:
286
+ alternatives = self.all_alternatives()
287
+ func_entry = PyrexTypes.best_match(
288
+ arg_types, alternatives, fail_if_empty=fail_if_empty, arg_is_lvalue_array=arg_is_lvalue_array)
289
+ return func_entry
290
+
291
+ def all_entries(self):
292
+ return [self] + self.inner_entries
293
+
294
+ def __lt__(left, right):
295
+ if isinstance(left, Entry) and isinstance(right, Entry):
296
+ return (left.name, left.cname) < (right.name, right.cname)
297
+ else:
298
+ return NotImplemented
299
+
300
+ @property
301
+ def cf_is_reassigned(self):
302
+ return len(self.cf_assignments) > 1
303
+
304
+ def make_cpp_optional(self):
305
+ assert self.type.is_cpp_class
306
+ self.is_cpp_optional = True
307
+ assert not self.utility_code # we're not overwriting anything?
308
+ self.utility_code_definition = Code.UtilityCode.load_cached("OptionalLocals", "CppSupport.cpp")
309
+
310
+ def declared_with_pytyping_modifier(self, modifier_name):
311
+ return modifier_name in self.pytyping_modifiers if self.pytyping_modifiers else False
312
+
313
+
314
+ class InnerEntry(Entry):
315
+ """
316
+ An entry in a closure scope that represents the real outer Entry.
317
+ """
318
+ from_closure = True
319
+
320
+ def __init__(self, outer_entry, scope):
321
+ Entry.__init__(self, outer_entry.name,
322
+ outer_entry.cname,
323
+ outer_entry.type,
324
+ outer_entry.pos)
325
+ self.outer_entry = outer_entry
326
+ self.scope = scope
327
+
328
+ # share state with (outermost) defining entry
329
+ outermost_entry = outer_entry
330
+ while outermost_entry.outer_entry:
331
+ outermost_entry = outermost_entry.outer_entry
332
+ self.defining_entry = outermost_entry
333
+ self.inner_entries = outermost_entry.inner_entries
334
+ self.cf_assignments = outermost_entry.cf_assignments
335
+ self.cf_references = outermost_entry.cf_references
336
+ self.overloaded_alternatives = outermost_entry.overloaded_alternatives
337
+ self.is_cpp_optional = outermost_entry.is_cpp_optional
338
+ self.inner_entries.append(self)
339
+
340
+ def __getattr__(self, name):
341
+ if name.startswith('__'):
342
+ # we wouldn't have been called if it was there
343
+ raise AttributeError(name)
344
+ return getattr(self.defining_entry, name)
345
+
346
+ def all_entries(self):
347
+ return self.defining_entry.all_entries()
348
+
349
+
350
+ class Scope:
351
+ # name string Unqualified name
352
+ # outer_scope Scope or None Enclosing scope
353
+ # entries {string : Entry} Python name to entry, non-types
354
+ # const_entries [Entry] Constant entries
355
+ # type_entries [Entry] Struct/union/enum/typedef/exttype entries
356
+ # sue_entries [Entry] Struct/union/enum entries
357
+ # arg_entries [Entry] Function argument entries
358
+ # var_entries [Entry] User-defined variable entries
359
+ # pyfunc_entries [Entry] Python function entries
360
+ # cfunc_entries [Entry] C function entries
361
+ # c_class_entries [Entry] All extension type entries
362
+ # cname_to_entry {string : Entry} Temp cname to entry mapping
363
+ # return_type PyrexType or None Return type of function owning scope
364
+ # is_builtin_scope boolean Is the builtin scope of Python/Cython
365
+ # is_py_class_scope boolean Is a Python class scope
366
+ # is_c_class_scope boolean Is an extension type scope
367
+ # is_local_scope boolean Is a local (i.e. function/method/generator) scope
368
+ # is_closure_scope boolean Is a closure scope
369
+ # is_generator_expression_scope boolean A subset of closure scope used for generator expressions
370
+ # is_passthrough boolean Outer scope is passed directly
371
+ # is_cpp_class_scope boolean Is a C++ class scope
372
+ # is_property_scope boolean Is a extension type property scope
373
+ # is_c_dataclass_scope boolean or "frozen" is a cython.dataclasses.dataclass
374
+ # scope_prefix string Disambiguator for C names
375
+ # in_cinclude boolean Suppress C declaration code
376
+ # qualified_name string "modname" or "modname.classname"
377
+ # Python strings in this scope
378
+ # nogil boolean In a nogil section
379
+ # directives dict Helper variable for the recursive
380
+ # analysis, contains directive values.
381
+ # is_internal boolean Is only used internally (simpler setup)
382
+ # scope_predefined_names list of str Class variable containing special names defined by
383
+ # this type of scope (e.g. __builtins__, __qualname__)
384
+ # node_positions_to_offset {pos: offset} Mapping from node positions to line table offsets
385
+
386
+ is_builtin_scope = 0
387
+ is_py_class_scope = 0
388
+ is_c_class_scope = 0
389
+ is_closure_scope = 0
390
+ is_local_scope = False
391
+ is_generator_expression_scope = 0
392
+ is_comprehension_scope = 0
393
+ is_passthrough = 0
394
+ is_cpp_class_scope = 0
395
+ is_property_scope = 0
396
+ is_module_scope = 0
397
+ is_c_dataclass_scope = False
398
+ is_internal = 0
399
+ scope_prefix = ""
400
+ in_cinclude = 0
401
+ nogil = 0
402
+ fused_to_specific = None
403
+ return_type = None
404
+ scope_predefined_names = []
405
+ # Do ambiguous type names like 'int' and 'float' refer to the C types? (Otherwise, Python types.)
406
+ in_c_type_context = True
407
+ node_positions_to_offset = {} # read-only fallback dict
408
+
409
+ def __init__(self, name, outer_scope, parent_scope):
410
+ # The outer_scope is the next scope in the lookup chain.
411
+ # The parent_scope is used to derive the qualified name of this scope.
412
+ self.name = name
413
+ self.outer_scope = outer_scope
414
+ self.parent_scope = parent_scope
415
+ mangled_name = "%d%s_" % (len(name), name.replace('.', '_dot_'))
416
+ qual_scope = self.qualifying_scope()
417
+ if qual_scope:
418
+ self.qualified_name = qual_scope.qualify_name(name)
419
+ self.scope_prefix = qual_scope.scope_prefix + mangled_name
420
+ else:
421
+ self.qualified_name = EncodedString(name)
422
+ self.scope_prefix = mangled_name
423
+ self.entries = {}
424
+ self.subscopes = set()
425
+ self.const_entries = []
426
+ self.type_entries = []
427
+ self.sue_entries = []
428
+ self.arg_entries = []
429
+ self.var_entries = []
430
+ self.pyfunc_entries = []
431
+ self.cfunc_entries = []
432
+ self.c_class_entries = []
433
+ self.defined_c_classes = []
434
+ self.imported_c_classes = {}
435
+ self.cname_to_entry = {}
436
+ self.identifier_to_entry = {}
437
+ self.num_to_entry = {}
438
+ self.obj_to_entry = {}
439
+ self.buffer_entries = []
440
+ self.lambda_defs = []
441
+ self.id_counters = {}
442
+ for var_name in self.scope_predefined_names:
443
+ self.declare_var(EncodedString(var_name), py_object_type, pos=None)
444
+
445
+ def __deepcopy__(self, memo):
446
+ return self
447
+
448
+ def merge_in(self, other, merge_unused=True, allowlist=None):
449
+ # Use with care...
450
+ entries = []
451
+ for name, entry in other.entries.items():
452
+ if not allowlist or name in allowlist:
453
+ if entry.used or merge_unused:
454
+ entries.append((name, entry))
455
+
456
+ self.entries.update(entries)
457
+
458
+ for attr in ('const_entries',
459
+ 'type_entries',
460
+ 'sue_entries',
461
+ 'arg_entries',
462
+ 'var_entries',
463
+ 'pyfunc_entries',
464
+ 'cfunc_entries',
465
+ 'c_class_entries'):
466
+ self_entries = getattr(self, attr)
467
+ names = {e.name for e in self_entries}
468
+ for entry in getattr(other, attr):
469
+ if (entry.used or merge_unused) and entry.name not in names:
470
+ self_entries.append(entry)
471
+
472
+ def __str__(self):
473
+ return "<%s %s>" % (self.__class__.__name__, self.qualified_name)
474
+
475
+ def qualifying_scope(self):
476
+ return self.parent_scope
477
+
478
+ def mangle(self, prefix, name = None):
479
+ if name:
480
+ return punycodify_name("%s%s%s" % (prefix, self.scope_prefix, name))
481
+ else:
482
+ return self.parent_scope.mangle(prefix, self.name)
483
+
484
+ def mangle_internal(self, name):
485
+ # Mangle an internal name so as not to clash with any
486
+ # user-defined name in this scope.
487
+ prefix = "%s%s_" % (Naming.pyrex_prefix, name)
488
+ return self.mangle(prefix)
489
+ #return self.parent_scope.mangle(prefix, self.name)
490
+
491
+ def mangle_class_private_name(self, name):
492
+ if self.parent_scope:
493
+ return self.parent_scope.mangle_class_private_name(name)
494
+ return name
495
+
496
+ def next_id(self, name=None):
497
+ # Return a cname fragment that is unique for this module
498
+ counters = self.global_scope().id_counters
499
+ try:
500
+ count = counters[name] + 1
501
+ except KeyError:
502
+ count = 0
503
+ counters[name] = count
504
+ if name:
505
+ if not count:
506
+ # unique names don't need a suffix, reoccurrences will get one
507
+ return name
508
+ return '%s%d' % (name, count)
509
+ else:
510
+ return '%d' % count
511
+
512
+ @property
513
+ def context(self):
514
+ return self.global_scope().context
515
+
516
+ def global_scope(self):
517
+ """ Return the module-level scope containing this scope. """
518
+ return self.outer_scope.global_scope()
519
+
520
+ def builtin_scope(self):
521
+ """ Return the module-level scope containing this scope. """
522
+ return self.outer_scope.builtin_scope()
523
+
524
+ def iter_local_scopes(self):
525
+ yield self
526
+ if self.subscopes:
527
+ yield from sorted(self.subscopes, key=operator.attrgetter('scope_prefix'))
528
+
529
+ @try_finally_contextmanager
530
+ def new_c_type_context(self, in_c_type_context=None):
531
+ old_c_type_context = self.in_c_type_context
532
+ if in_c_type_context is not None:
533
+ self.in_c_type_context = in_c_type_context
534
+ yield
535
+ self.in_c_type_context = old_c_type_context
536
+
537
+ def handle_already_declared_name(self, name, cname, type, pos, visibility, copy_entry=False):
538
+ """
539
+ Returns an entry or None
540
+
541
+ If it returns an entry, it makes sense for "declare" to keep using that
542
+ entry and not to declare its own.
543
+
544
+ May be overridden (e.g. for builtin scope,
545
+ which always allows redeclarations)
546
+ """
547
+ entry = None
548
+ entries = self.entries
549
+ old_entry = entries[name]
550
+
551
+ # Reject redeclared C++ functions only if they have a compatible type signature.
552
+ cpp_override_allowed = False
553
+ if type.is_cfunction and old_entry.type.is_cfunction and self.is_cpp():
554
+ # If we redefine a C++ class method which is either inherited
555
+ # or automatically generated (base constructor), then it's fine.
556
+ # Otherwise, we shout.
557
+ for alt_entry in old_entry.all_alternatives():
558
+ if type.compatible_signature_with(alt_entry.type):
559
+ if name == '<init>' and not type.args:
560
+ # Cython pre-declares the no-args constructor - allow later user definitions.
561
+ cpp_override_allowed = True
562
+ elif alt_entry.is_inherited:
563
+ # Note that we can override an inherited method with a compatible but not exactly equal signature, as in C++.
564
+ cpp_override_allowed = True
565
+ if cpp_override_allowed:
566
+ entry = alt_entry
567
+ if copy_entry:
568
+ entry = copy.copy(alt_entry)
569
+
570
+ # A compatible signature doesn't mean the exact same signature,
571
+ # so we're taking the new signature for the entry.
572
+ entry.type = type
573
+ entry.is_inherited = False
574
+ # Updating the entry attributes which can be modified in the method redefinition.
575
+ entry.cname = cname
576
+ entry.pos = pos
577
+ break
578
+ else:
579
+ cpp_override_allowed = True
580
+
581
+ if cpp_override_allowed:
582
+ # C++ function/method overrides with different signatures are ok.
583
+ pass
584
+ elif entries[name].is_inherited:
585
+ # Likewise ignore inherited classes.
586
+ pass
587
+ else:
588
+ if visibility == 'extern':
589
+ # Silenced outside of "cdef extern" blocks, until we have a safe way to
590
+ # prevent pxd-defined cpdef functions from ending up here.
591
+ warning(pos, "'%s' redeclared " % name, 1 if self.in_cinclude else 0)
592
+ elif visibility != 'ignore':
593
+ error(pos, "'%s' redeclared " % name)
594
+ self.entries[name].already_declared_here()
595
+ return None
596
+
597
+ return entry
598
+
599
+
600
+ def declare(self, name, cname, type, pos, visibility, shadow = 0, is_type = 0, create_wrapper = 0):
601
+ # Create new entry, and add to dictionary if
602
+ # name is not None. Reports a warning if already
603
+ # declared.
604
+ if type.is_buffer and not isinstance(self, LocalScope): # and not is_type:
605
+ error(pos, 'Buffer types only allowed as function local variables')
606
+ if not self.in_cinclude and cname and re.match("^_[_A-Z]+$", cname):
607
+ # See https://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html#Reserved-Names
608
+ warning(pos, "'%s' is a reserved name in C." % cname, -1)
609
+
610
+ entries = self.entries
611
+ entry = None
612
+ if name and name in entries and not shadow:
613
+ entry = self.handle_already_declared_name(name, cname, type, pos, visibility)
614
+
615
+ if not entry:
616
+ entry = Entry(name, cname, type, pos = pos)
617
+ entry.in_cinclude = self.in_cinclude
618
+ entry.create_wrapper = create_wrapper
619
+
620
+ if name:
621
+ entry.qualified_name = self.qualify_name(name)
622
+ if not shadow:
623
+ if name in entries and self.is_cpp() and type.is_cfunction and not entries[name].is_cmethod:
624
+ # Which means: function or cppclass method is already present
625
+ entries[name].overloaded_alternatives.append(entry)
626
+ else:
627
+ entries[name] = entry
628
+
629
+ if type.is_memoryviewslice:
630
+ entry.init = type.default_value
631
+
632
+ entry.scope = self
633
+ entry.visibility = visibility
634
+ return entry
635
+
636
+ def qualify_name(self, name):
637
+ return EncodedString("%s.%s" % (self.qualified_name, name))
638
+
639
+ def declare_const(self, name, type, value, pos, cname = None, visibility = 'private', api = 0, create_wrapper = 0):
640
+ # Add an entry for a named constant.
641
+ if not cname:
642
+ if self.in_cinclude or (visibility == 'public' or api):
643
+ cname = name
644
+ else:
645
+ cname = self.mangle(Naming.enum_prefix, name)
646
+ entry = self.declare(name, cname, type, pos, visibility, create_wrapper = create_wrapper)
647
+ entry.is_const = 1
648
+ entry.value_node = value
649
+ return entry
650
+
651
+ def declare_type(self, name, type, pos,
652
+ cname = None, visibility = 'private', api = 0, defining = 1,
653
+ shadow = 0, template = 0):
654
+ # Add an entry for a type definition.
655
+ if not cname:
656
+ cname = name
657
+ entry = self.declare(name, cname, type, pos, visibility, shadow,
658
+ is_type=True)
659
+ entry.is_type = 1
660
+ entry.api = api
661
+ if defining:
662
+ self.type_entries.append(entry)
663
+
664
+ # don't replace an entry that's already set
665
+ if not template and getattr(type, "entry", None) is None:
666
+ type.entry = entry
667
+
668
+ # here we would set as_variable to an object representing this type
669
+ return entry
670
+
671
+ def declare_typedef(self, name, base_type, pos, cname = None,
672
+ visibility = 'private', api = 0):
673
+ if not cname:
674
+ if self.in_cinclude or (visibility != 'private' or api):
675
+ cname = name
676
+ else:
677
+ cname = self.mangle(Naming.type_prefix, name)
678
+ try:
679
+ if self.is_cpp_class_scope:
680
+ namespace = self.outer_scope.lookup(self.name).type
681
+ else:
682
+ namespace = None
683
+ type = PyrexTypes.create_typedef_type(name, base_type, cname,
684
+ (visibility == 'extern'),
685
+ namespace)
686
+ except ValueError as e:
687
+ error(pos, e.args[0])
688
+ type = PyrexTypes.error_type
689
+ entry = self.declare_type(name, type, pos, cname,
690
+ visibility = visibility, api = api)
691
+ type.qualified_name = entry.qualified_name
692
+ return entry
693
+
694
+ def declare_struct_or_union(self, name, kind, scope,
695
+ typedef_flag, pos, cname = None,
696
+ visibility = 'private', api = 0,
697
+ packed = False):
698
+ # Add an entry for a struct or union definition.
699
+ if not cname:
700
+ if self.in_cinclude or (visibility == 'public' or api):
701
+ cname = name
702
+ else:
703
+ cname = self.mangle(Naming.type_prefix, name)
704
+ entry = self.lookup_here(name)
705
+ if not entry:
706
+ in_cpp = self.is_cpp()
707
+ type = PyrexTypes.CStructOrUnionType(
708
+ name, kind, scope, typedef_flag, cname, packed,
709
+ in_cpp = in_cpp)
710
+ entry = self.declare_type(name, type, pos, cname,
711
+ visibility = visibility, api = api,
712
+ defining = scope is not None)
713
+ self.sue_entries.append(entry)
714
+ type.entry = entry
715
+ else:
716
+ if not (entry.is_type and entry.type.is_struct_or_union
717
+ and entry.type.kind == kind):
718
+ warning(pos, "'%s' redeclared " % name, 0)
719
+ elif scope and entry.type.scope:
720
+ warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
721
+ else:
722
+ self.check_previous_typedef_flag(entry, typedef_flag, pos)
723
+ self.check_previous_visibility(entry, visibility, pos)
724
+ if scope:
725
+ entry.type.scope = scope
726
+ self.type_entries.append(entry)
727
+ if self.is_cpp_class_scope:
728
+ entry.type.namespace = self.outer_scope.lookup(self.name).type
729
+ return entry
730
+
731
+ def declare_cpp_class(self, name, scope,
732
+ pos, cname = None, base_classes = (),
733
+ visibility = 'extern', templates = None):
734
+ if cname is None:
735
+ if self.in_cinclude or (visibility != 'private'):
736
+ cname = name
737
+ else:
738
+ cname = self.mangle(Naming.type_prefix, name)
739
+ base_classes = list(base_classes)
740
+ entry = self.lookup_here(name)
741
+ if not entry:
742
+ type = PyrexTypes.CppClassType(
743
+ name, scope, cname, base_classes, templates = templates)
744
+ entry = self.declare_type(name, type, pos, cname,
745
+ visibility = visibility, defining = scope is not None)
746
+ self.sue_entries.append(entry)
747
+ else:
748
+ if not (entry.is_type and entry.type.is_cpp_class):
749
+ error(pos, "'%s' redeclared " % name)
750
+ entry.already_declared_here()
751
+ return None
752
+ elif scope and entry.type.scope:
753
+ warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
754
+ else:
755
+ if scope:
756
+ entry.type.scope = scope
757
+ self.type_entries.append(entry)
758
+ if base_classes:
759
+ if entry.type.base_classes and entry.type.base_classes != base_classes:
760
+ error(pos, "Base type does not match previous declaration")
761
+ entry.already_declared_here()
762
+ else:
763
+ entry.type.base_classes = base_classes
764
+ if templates or entry.type.templates:
765
+ if templates != entry.type.templates:
766
+ error(pos, "Template parameters do not match previous declaration")
767
+ entry.already_declared_here()
768
+
769
+ def declare_inherited_attributes(entry, base_classes):
770
+ for base_class in base_classes:
771
+ if base_class is PyrexTypes.error_type:
772
+ continue
773
+ if base_class.scope is None:
774
+ error(pos, "Cannot inherit from incomplete type")
775
+ else:
776
+ declare_inherited_attributes(entry, base_class.base_classes)
777
+ entry.type.scope.declare_inherited_cpp_attributes(base_class)
778
+ if scope:
779
+ declare_inherited_attributes(entry, base_classes)
780
+ scope.declare_var(name="this", cname="this", type=PyrexTypes.CPtrType(entry.type), pos=entry.pos)
781
+ if self.is_cpp_class_scope:
782
+ entry.type.namespace = self.outer_scope.lookup(self.name).type
783
+ return entry
784
+
785
+ def check_previous_typedef_flag(self, entry, typedef_flag, pos):
786
+ if typedef_flag != entry.type.typedef_flag:
787
+ error(pos, "'%s' previously declared using '%s'" % (
788
+ entry.name, ("cdef", "ctypedef")[entry.type.typedef_flag]))
789
+
790
+ def check_previous_visibility(self, entry, visibility, pos):
791
+ if entry.visibility != visibility:
792
+ error(pos, "'%s' previously declared as '%s'" % (
793
+ entry.name, entry.visibility))
794
+
795
+ def declare_enum(self, name, pos, cname, scoped, typedef_flag,
796
+ visibility='private', api=0, create_wrapper=0, doc=None):
797
+ if name:
798
+ if not cname:
799
+ if (self.in_cinclude or visibility == 'public'
800
+ or visibility == 'extern' or api):
801
+ cname = name
802
+ else:
803
+ cname = self.mangle(Naming.type_prefix, name)
804
+ if self.is_cpp_class_scope:
805
+ namespace = self.outer_scope.lookup(self.name).type
806
+ else:
807
+ namespace = None
808
+
809
+ if scoped:
810
+ type = PyrexTypes.CppScopedEnumType(name, cname, namespace, doc=doc)
811
+ else:
812
+ type = PyrexTypes.CEnumType(name, cname, typedef_flag, namespace, doc=doc)
813
+ else:
814
+ type = PyrexTypes.c_anon_enum_type
815
+ entry = self.declare_type(name, type, pos, cname = cname,
816
+ visibility = visibility, api = api)
817
+ if scoped:
818
+ entry.utility_code = Code.UtilityCode.load_cached("EnumClassDecl", "CppSupport.cpp")
819
+ self.use_entry_utility_code(entry)
820
+ entry.create_wrapper = create_wrapper
821
+ entry.enum_values = []
822
+
823
+ self.sue_entries.append(entry)
824
+ return entry
825
+
826
+ def declare_tuple_type(self, pos, components):
827
+ return self.outer_scope.declare_tuple_type(pos, components)
828
+
829
+ def declare_var(self, name, type, pos,
830
+ cname=None, visibility='private',
831
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None):
832
+ # Add an entry for a variable.
833
+ if not cname:
834
+ if visibility != 'private' or api:
835
+ cname = name
836
+ else:
837
+ cname = self.mangle(Naming.var_prefix, name)
838
+ entry = self.declare(name, cname, type, pos, visibility)
839
+ entry.is_variable = 1
840
+ if type.is_cpp_class and visibility != 'extern':
841
+ if self.directives['cpp_locals']:
842
+ entry.make_cpp_optional()
843
+ else:
844
+ type.check_nullary_constructor(pos)
845
+ if in_pxd and visibility != 'extern':
846
+ entry.defined_in_pxd = 1
847
+ entry.used = 1
848
+ if api:
849
+ entry.api = 1
850
+ entry.used = 1
851
+ if pytyping_modifiers:
852
+ entry.pytyping_modifiers = pytyping_modifiers
853
+ return entry
854
+
855
+ def _reject_pytyping_modifiers(self, pos, modifiers, allowed=()):
856
+ if not modifiers:
857
+ return
858
+ for modifier in modifiers:
859
+ if modifier not in allowed:
860
+ error(pos, "Modifier '%s' is not allowed here." % modifier)
861
+
862
+ def declare_assignment_expression_target(self, name, type, pos):
863
+ # In most cases declares the variable as normal.
864
+ # For generator expressions and comprehensions the variable is declared in their parent
865
+ return self.declare_var(name, type, pos)
866
+
867
+ def declare_builtin(self, name, pos):
868
+ name = self.mangle_class_private_name(name)
869
+ return self.outer_scope.declare_builtin(name, pos)
870
+
871
+ def _declare_pyfunction(self, name, pos, visibility='extern', entry=None):
872
+ if entry and not entry.type.is_cfunction:
873
+ error(pos, "'%s' already declared" % name)
874
+ error(entry.pos, "Previous declaration is here")
875
+ entry = self.declare_var(name, py_object_type, pos, visibility=visibility)
876
+ entry.signature = pyfunction_signature
877
+ self.pyfunc_entries.append(entry)
878
+ return entry
879
+
880
+ def declare_pyfunction(self, name, pos, allow_redefine=False, visibility='extern'):
881
+ # Add an entry for a Python function.
882
+ entry = self.lookup_here(name)
883
+ if not allow_redefine:
884
+ return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
885
+ if entry:
886
+ if entry.type.is_unspecified:
887
+ entry.type = py_object_type
888
+ elif entry.type is not py_object_type:
889
+ return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
890
+ else: # declare entry stub
891
+ self.declare_var(name, py_object_type, pos, visibility=visibility)
892
+ entry = self.declare_var(None, py_object_type, pos,
893
+ cname=name, visibility='private')
894
+ entry.name = EncodedString(name)
895
+ entry.qualified_name = self.qualify_name(name)
896
+ entry.signature = pyfunction_signature
897
+ entry.is_anonymous = True
898
+ return entry
899
+
900
+ def declare_lambda_function(self, lambda_name, pos):
901
+ # Add an entry for an anonymous Python function.
902
+ func_cname = self.mangle(Naming.lambda_func_prefix + 'funcdef_', lambda_name)
903
+ pymethdef_cname = self.mangle(Naming.lambda_func_prefix + 'methdef_', lambda_name)
904
+ qualified_name = self.qualify_name(lambda_name)
905
+
906
+ entry = self.declare(None, func_cname, py_object_type, pos, 'private')
907
+ entry.name = EncodedString(lambda_name)
908
+ entry.qualified_name = qualified_name
909
+ entry.pymethdef_cname = pymethdef_cname
910
+ entry.func_cname = func_cname
911
+ entry.signature = pyfunction_signature
912
+ entry.is_anonymous = True
913
+ return entry
914
+
915
+ def add_lambda_def(self, def_node):
916
+ self.lambda_defs.append(def_node)
917
+
918
+ def register_pyfunction(self, entry):
919
+ self.pyfunc_entries.append(entry)
920
+
921
+ def declare_cfunction(self, name, type, pos,
922
+ cname=None, visibility='private', api=0, in_pxd=0,
923
+ defining=0, modifiers=(), utility_code=None, overridable=False):
924
+ # Add an entry for a C function.
925
+ if not cname:
926
+ if visibility != 'private' or api:
927
+ cname = name
928
+ else:
929
+ cname = self.mangle(Naming.func_prefix, name)
930
+ inline_in_pxd = 'inline' in modifiers and in_pxd and defining
931
+ if inline_in_pxd:
932
+ # in_pxd does special things that we don't want to apply to inline functions
933
+ in_pxd = False
934
+ entry = self.lookup_here(name)
935
+ if entry:
936
+ if not in_pxd and visibility != entry.visibility and visibility == 'extern':
937
+ # Previously declared, but now extern => treat this
938
+ # as implementing the function, using the new cname
939
+ defining = True
940
+ visibility = entry.visibility
941
+ entry.cname = cname
942
+ entry.func_cname = cname
943
+ if visibility != 'private' and visibility != entry.visibility:
944
+ warning(pos, "Function '%s' previously declared as '%s', now as '%s'" % (
945
+ name, entry.visibility, visibility), 1)
946
+ if overridable != entry.is_overridable:
947
+ warning(pos, "Function '%s' previously declared as '%s'" % (
948
+ name, 'cpdef' if overridable else 'cdef'), 1)
949
+ if entry.type.same_as(type):
950
+ # Fix with_gil vs nogil.
951
+ entry.type = entry.type.with_with_gil(type.with_gil)
952
+ else:
953
+ if visibility == 'extern' and entry.visibility == 'extern':
954
+ can_override = self.is_builtin_scope
955
+ if self.is_cpp():
956
+ can_override = True
957
+ elif cname and not can_override:
958
+ # if all alternatives have different cnames,
959
+ # it's safe to allow signature overrides
960
+ for alt_entry in entry.all_alternatives():
961
+ if not alt_entry.cname or cname == alt_entry.cname:
962
+ break # cname not unique!
963
+ else:
964
+ can_override = True
965
+ if can_override:
966
+ temp = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
967
+ temp.overloaded_alternatives = entry.all_alternatives()
968
+ if entry.specialiser is not None:
969
+ temp.specialiser = entry.specialiser
970
+ entry = temp
971
+ else:
972
+ warning(pos, "Function signature does not match previous declaration", 1)
973
+ entry.type = type
974
+ elif not in_pxd and entry.defined_in_pxd and type.compatible_signature_with(entry.type):
975
+ # TODO: check that this was done by a signature optimisation and not a user error.
976
+ #warning(pos, "Function signature does not match previous declaration", 1)
977
+
978
+ # Cython can't assume anything about cimported functions declared without
979
+ # an exception value. This is a performance problem mainly for nogil functions.
980
+ if entry.type.nogil and entry.type.exception_value is None and type.exception_value:
981
+ performance_hint(
982
+ entry.pos,
983
+ f"No exception value declared for '{entry.name}' in pxd file.\n"
984
+ "Users cimporting this function and calling it without the gil "
985
+ "will always require an exception check.\n"
986
+ "Suggest adding an explicit exception value.",
987
+ self)
988
+ entry.type = type
989
+ else:
990
+ error(pos, "Function signature does not match previous declaration")
991
+ else:
992
+ entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
993
+ entry.func_cname = cname
994
+ entry.is_overridable = overridable
995
+ if inline_in_pxd:
996
+ entry.inline_func_in_pxd = True
997
+ if in_pxd and visibility != 'extern':
998
+ entry.defined_in_pxd = 1
999
+ if api:
1000
+ entry.api = 1
1001
+ if not defining and not in_pxd and visibility != 'extern':
1002
+ error(pos, "Non-extern C function '%s' declared but not defined" % name)
1003
+ if defining:
1004
+ entry.is_implemented = True
1005
+ if modifiers:
1006
+ entry.func_modifiers = modifiers
1007
+ if utility_code:
1008
+ assert not entry.utility_code, "duplicate utility code definition in entry %s (%s)" % (name, cname)
1009
+ entry.utility_code = utility_code
1010
+ if overridable:
1011
+ # names of cpdef functions can be used as variables and can be assigned to
1012
+ var_entry = Entry(name, cname, py_object_type) # FIXME: cname?
1013
+ var_entry.qualified_name = self.qualify_name(name)
1014
+ var_entry.is_variable = 1
1015
+ var_entry.is_pyglobal = 1
1016
+ var_entry.scope = entry.scope
1017
+ entry.as_variable = var_entry
1018
+ type.entry = entry
1019
+ if (type.exception_check and type.exception_value is None and type.nogil and
1020
+ not pos[0].in_utility_code and
1021
+ # don't warn about external functions here - the user likely can't do anything
1022
+ defining and not in_pxd and not inline_in_pxd):
1023
+ PyrexTypes.write_noexcept_performance_hint(
1024
+ pos, self, function_name=name, void_return=type.return_type.is_void)
1025
+ return entry
1026
+
1027
+ def declare_cgetter(self, name, return_type, pos=None, cname=None,
1028
+ visibility="private", modifiers=(), defining=False, **cfunc_type_config):
1029
+ assert all(
1030
+ k in ('exception_value', 'exception_check', 'nogil', 'with_gil', 'is_const_method', 'is_static_method')
1031
+ for k in cfunc_type_config
1032
+ )
1033
+ cfunc_type = PyrexTypes.CFuncType(
1034
+ return_type,
1035
+ [PyrexTypes.CFuncTypeArg("self", self.parent_type, None)],
1036
+ **cfunc_type_config)
1037
+ entry = self.declare_cfunction(
1038
+ name, cfunc_type, pos, cname=None, visibility=visibility, modifiers=modifiers, defining=defining)
1039
+ entry.is_cgetter = True
1040
+ if cname is not None:
1041
+ entry.func_cname = cname
1042
+ return entry
1043
+
1044
+ def add_cfunction(self, name, type, pos, cname, visibility, modifiers, inherited=False):
1045
+ # Add a C function entry without giving it a func_cname.
1046
+ entry = self.declare(name, cname, type, pos, visibility)
1047
+ entry.is_cfunction = 1
1048
+ if modifiers:
1049
+ entry.func_modifiers = modifiers
1050
+ if inherited or type.is_fused:
1051
+ self.cfunc_entries.append(entry)
1052
+ else:
1053
+ # For backwards compatibility reasons, we must keep all non-fused methods
1054
+ # before all fused methods, but separately for each type.
1055
+ i = len(self.cfunc_entries)
1056
+ for cfunc_entry in reversed(self.cfunc_entries):
1057
+ if cfunc_entry.is_inherited or not cfunc_entry.type.is_fused:
1058
+ break
1059
+ i -= 1
1060
+ self.cfunc_entries.insert(i, entry)
1061
+ return entry
1062
+
1063
+ def find(self, name, pos):
1064
+ # Look up name, report error if not found.
1065
+ entry = self.lookup(name)
1066
+ if entry:
1067
+ return entry
1068
+ else:
1069
+ error(pos, "'%s' is not declared" % name)
1070
+
1071
+ def find_imported_module(self, path, pos):
1072
+ # Look up qualified name, must be a module, report error if not found.
1073
+ # Path is a list of names.
1074
+ scope = self
1075
+ for name in path:
1076
+ entry = scope.find(name, pos)
1077
+ if not entry:
1078
+ return None
1079
+ if entry.as_module:
1080
+ scope = entry.as_module
1081
+ else:
1082
+ error(pos, "'%s' is not a cimported module" % '.'.join(path))
1083
+ return None
1084
+ return scope
1085
+
1086
+ def lookup(self, name):
1087
+ # Look up name in this scope or an enclosing one.
1088
+ # Return None if not found.
1089
+
1090
+ mangled_name = self.mangle_class_private_name(name)
1091
+ entry = (self.lookup_here(name) # lookup here also does mangling
1092
+ or (self.outer_scope and self.outer_scope.lookup(mangled_name))
1093
+ or None)
1094
+ if entry:
1095
+ return entry
1096
+
1097
+ # look up the original name in the outer scope
1098
+ # Not strictly Python behaviour but see https://github.com/cython/cython/issues/3544
1099
+ entry = (self.outer_scope and self.outer_scope.lookup(name)) or None
1100
+ if entry and entry.is_pyglobal:
1101
+ self._emit_class_private_warning(entry.pos, name)
1102
+ return entry
1103
+
1104
+ def lookup_here(self, name):
1105
+ # Look up in this scope only, return None if not found.
1106
+
1107
+ entry = self.entries.get(self.mangle_class_private_name(name), None)
1108
+ if entry:
1109
+ return entry
1110
+ # Also check the unmangled name in the current scope
1111
+ # (even if mangling should give us something else).
1112
+ # This is to support things like global __foo which makes a declaration for __foo
1113
+ return self.entries.get(name, None)
1114
+
1115
+ def lookup_here_unmangled(self, name):
1116
+ return self.entries.get(name, None)
1117
+
1118
+ def lookup_assignment_expression_target(self, name):
1119
+ # For most cases behaves like "lookup_here".
1120
+ # However, it does look outwards for comprehension and generator expression scopes
1121
+ return self.lookup_here(name)
1122
+
1123
+ def lookup_target(self, name):
1124
+ # Look up name in this scope only. Declare as Python
1125
+ # variable if not found.
1126
+ entry = self.lookup_here(name)
1127
+ if not entry:
1128
+ entry = self.lookup_here_unmangled(name)
1129
+ if entry and entry.is_pyglobal:
1130
+ self._emit_class_private_warning(entry.pos, name)
1131
+ if not entry:
1132
+ entry = self.declare_var(name, py_object_type, None)
1133
+ return entry
1134
+
1135
+ def _type_or_specialized_type_from_entry(self, entry):
1136
+ if entry and entry.is_type:
1137
+ if entry.type.is_fused and self.fused_to_specific:
1138
+ return entry.type.specialize(self.fused_to_specific)
1139
+ return entry.type
1140
+ return None
1141
+
1142
+ def lookup_type(self, name):
1143
+ entry = self.lookup(name)
1144
+ # The logic here is:
1145
+ # 1. if entry is a type then return it (and maybe specialize it)
1146
+ # 2. if the entry comes from a known standard library import then follow that
1147
+ # 3. repeat step 1 with the (possibly) updated entry
1148
+
1149
+ tp = self._type_or_specialized_type_from_entry(entry)
1150
+ if tp:
1151
+ return tp
1152
+ # allow us to find types from the "typing" module and similar
1153
+ if entry and entry.known_standard_library_import:
1154
+ from .Builtin import get_known_standard_library_entry
1155
+ entry = get_known_standard_library_entry(entry.known_standard_library_import)
1156
+ return self._type_or_specialized_type_from_entry(entry)
1157
+
1158
+ def lookup_operator(self, operator, operands):
1159
+ if operands[0].type.is_cpp_class:
1160
+ obj_type = operands[0].type
1161
+ method = obj_type.scope.lookup("operator%s" % operator)
1162
+ if method is not None:
1163
+ arg_types = [arg.type for arg in operands[1:]]
1164
+ res = PyrexTypes.best_match(arg_types, method.all_alternatives())
1165
+ if res is not None:
1166
+ return res
1167
+ function = self.lookup("operator%s" % operator)
1168
+ function_alternatives = []
1169
+ if function is not None:
1170
+ function_alternatives = function.all_alternatives()
1171
+
1172
+ # look-up nonmember methods listed within a class
1173
+ method_alternatives = []
1174
+ if len(operands) == 2: # binary operators only
1175
+ for n in range(2):
1176
+ if operands[n].type.is_cpp_class:
1177
+ obj_type = operands[n].type
1178
+ method = obj_type.scope.lookup("operator%s" % operator)
1179
+ if method is not None:
1180
+ method_alternatives += method.all_alternatives()
1181
+
1182
+ if (not method_alternatives) and (not function_alternatives):
1183
+ return None
1184
+
1185
+ # select the unique alternatives
1186
+ all_alternatives = list(set(method_alternatives + function_alternatives))
1187
+
1188
+ return PyrexTypes.best_match([arg.type for arg in operands],
1189
+ all_alternatives)
1190
+
1191
+ def lookup_operator_for_types(self, pos, operator, types):
1192
+ from .Nodes import Node
1193
+ class FakeOperand(Node):
1194
+ pass
1195
+ operands = [FakeOperand(pos, type=type) for type in types]
1196
+ return self.lookup_operator(operator, operands)
1197
+
1198
+ def _emit_class_private_warning(self, pos, name):
1199
+ warning(pos, "Global name %s matched from within class scope "
1200
+ "in contradiction to Python 'class private name' rules. "
1201
+ "This may change in a future release." % name, 1)
1202
+
1203
+ def use_utility_code(self, new_code):
1204
+ self.global_scope().use_utility_code(new_code)
1205
+
1206
+ def use_entry_utility_code(self, entry):
1207
+ self.global_scope().use_entry_utility_code(entry)
1208
+
1209
+ def defines_any(self, names):
1210
+ # Test whether any of the given names are defined in this scope.
1211
+ for name in names:
1212
+ if name in self.entries:
1213
+ return 1
1214
+ return 0
1215
+
1216
+ def defines_any_special(self, names):
1217
+ # Test whether any of the given names are defined as special methods in this scope.
1218
+ for name in names:
1219
+ if name in self.entries and self.entries[name].is_special:
1220
+ return 1
1221
+ return 0
1222
+
1223
+ def infer_types(self):
1224
+ from .TypeInference import get_type_inferer
1225
+ get_type_inferer().infer_types(self)
1226
+
1227
+ def is_cpp(self):
1228
+ outer = self.outer_scope
1229
+ if outer is None:
1230
+ return False
1231
+ else:
1232
+ return outer.is_cpp()
1233
+
1234
+ def add_include_file(self, filename, verbatim_include=None, late=False):
1235
+ self.outer_scope.add_include_file(filename, verbatim_include, late)
1236
+
1237
+ def name_in_module_state(self, cname):
1238
+ # TODO - override to give more choices depending on the type of scope
1239
+ # e.g. slot, function, method
1240
+ return f"{Naming.modulestateglobal_cname}->{cname}"
1241
+
1242
+ def find_shared_usages_of_type(self, type_to_find, _seen_scopes=None):
1243
+ if _seen_scopes is None:
1244
+ _seen_scopes = set()
1245
+ include_all_entries = not self.is_module_scope
1246
+ for entry in self.entries.values():
1247
+ if not (include_all_entries or entry.defined_in_pxd or entry.visibility == "public" or entry.api):
1248
+ continue
1249
+ entry_subtypes = PyrexTypes.get_all_subtypes(entry.type)
1250
+ if any(type_to_find == sub_tp for sub_tp in entry_subtypes):
1251
+ return True
1252
+ type_scope = getattr(entry.type, "scope", None)
1253
+ if type_scope is None or type_scope in _seen_scopes:
1254
+ continue
1255
+ _seen_scopes.add(type_scope)
1256
+ if type_scope.find_shared_usages_of_type(type_to_find, _seen_scopes):
1257
+ return True
1258
+ return False
1259
+
1260
+
1261
+ class PreImportScope(Scope):
1262
+
1263
+ namespace_cname = Naming.preimport_cname
1264
+
1265
+ def __init__(self):
1266
+ Scope.__init__(self, Options.pre_import, None, None)
1267
+
1268
+ def declare_builtin(self, name, pos):
1269
+ entry = self.declare(name, name, py_object_type, pos, 'private')
1270
+ entry.is_variable = True
1271
+ entry.is_pyglobal = True
1272
+ return entry
1273
+
1274
+
1275
+ class BuiltinScope(Scope):
1276
+ # The builtin namespace.
1277
+
1278
+ is_builtin_scope = True
1279
+
1280
+ def __init__(self):
1281
+ if Options.pre_import is None:
1282
+ Scope.__init__(self, "__builtin__", None, None)
1283
+ else:
1284
+ Scope.__init__(self, "__builtin__", PreImportScope(), None)
1285
+ self.type_names = {}
1286
+
1287
+ def lookup(self, name, language_level=None):
1288
+ # 'language_level' is passed by ModuleScope
1289
+ if name == 'unicode' or name == 'basestring':
1290
+ # Keep recognising 'unicode' and 'basestring' in legacy code but map them to 'str'.
1291
+ name = 'str'
1292
+ elif name == 'long' and language_level == 2:
1293
+ # Keep recognising 'long' in legacy Py2 code but map it to 'int'.
1294
+ name = 'int'
1295
+ return Scope.lookup(self, name)
1296
+
1297
+ def declare_builtin(self, name, pos):
1298
+ if name not in PyrexTypes.KNOWN_PYTHON_BUILTINS:
1299
+ if self.outer_scope is not None:
1300
+ return self.outer_scope.declare_builtin(name, pos)
1301
+ else:
1302
+ if Options.error_on_unknown_names:
1303
+ error(pos, "undeclared name not builtin: %s" % name)
1304
+ else:
1305
+ warning(pos, "undeclared name not builtin: %s" % name, 2)
1306
+
1307
+ def declare_builtin_cfunction(self, name, type, cname, python_equiv=None, utility_code=None, specialiser=None):
1308
+ # If python_equiv == "*", the Python equivalent has the same name
1309
+ # as the entry, otherwise it has the name specified by python_equiv.
1310
+ name = EncodedString(name)
1311
+ entry = self.declare_cfunction(name, type, None, cname, visibility='extern', utility_code=utility_code)
1312
+ if specialiser is not None:
1313
+ entry.specialiser = specialiser
1314
+ if python_equiv:
1315
+ if python_equiv == "*":
1316
+ python_equiv = name
1317
+ else:
1318
+ python_equiv = EncodedString(python_equiv)
1319
+ var_entry = Entry(python_equiv, python_equiv, py_object_type)
1320
+ var_entry.qualified_name = self.qualify_name(name)
1321
+ var_entry.is_variable = 1
1322
+ var_entry.is_builtin = 1
1323
+ var_entry.utility_code = utility_code
1324
+ var_entry.scope = entry.scope
1325
+ entry.as_variable = var_entry
1326
+ return entry
1327
+
1328
+ def declare_builtin_type(self, name, cname,
1329
+ objstruct_cname=None, type_class=PyrexTypes.BuiltinObjectType,
1330
+ utility_code=None):
1331
+ name = EncodedString(name)
1332
+ type = type_class(name, cname, objstruct_cname, type_check_utility_code=utility_code)
1333
+ scope = CClassScope(name, outer_scope=None, visibility='extern', parent_type=type)
1334
+ scope.directives = {}
1335
+ type.set_scope(scope)
1336
+ self.type_names[name] = 1
1337
+
1338
+ entry = self.declare_type(name, type, None, visibility='extern')
1339
+ if utility_code:
1340
+ entry.utility_code = utility_code
1341
+ if name == 'range' and 'xrange' not in self.entries:
1342
+ # Keep supporting legacy Py2 'xrange' because it's still in use.
1343
+ self.entries['xrange'] = entry
1344
+
1345
+ var_entry = Entry(
1346
+ name=entry.name,
1347
+ type=self.lookup('type').type, # make sure "type" is the first type declared...
1348
+ pos=entry.pos,
1349
+ cname=entry.type.typeptr_cname,
1350
+ )
1351
+ var_entry.qualified_name = self.qualify_name(name)
1352
+ var_entry.is_variable = 1
1353
+ var_entry.is_cglobal = 1
1354
+ var_entry.is_readonly = 1
1355
+ var_entry.is_builtin = 1
1356
+ var_entry.scope = self
1357
+ if Options.cache_builtins:
1358
+ var_entry.is_const = True
1359
+ if utility_code:
1360
+ var_entry.utility_code = utility_code
1361
+ entry.as_variable = var_entry
1362
+
1363
+ return type
1364
+
1365
+ def builtin_scope(self):
1366
+ return self
1367
+
1368
+ def handle_already_declared_name(self, name, cname, type, pos, visibility, copy_entry=False):
1369
+ # Overriding is OK in the builtin scope
1370
+ return None
1371
+
1372
+
1373
+ const_counter = 1 # As a temporary solution for compiling code in pxds
1374
+
1375
+ class ModuleScope(Scope):
1376
+ # module_name string Python name of the module
1377
+ # module_cname string C name of Python module object
1378
+ # #module_dict_cname string C name of module dict object
1379
+ # method_table_cname string C name of method table
1380
+ # doc string Module doc string
1381
+ # doc_cname string C name of module doc string
1382
+ # utility_code_list [UtilityCode] Queuing utility codes for forwarding to Code.py
1383
+ # c_includes {key: IncludeCode} C headers or verbatim code to be generated
1384
+ # See process_include() for more documentation
1385
+ # identifier_to_entry {string : Entry} Map identifier string const to entry
1386
+ # context Context
1387
+ # parent_module Scope Parent in the import namespace
1388
+ # module_entries {string : Entry} For cimport statements
1389
+ # type_names {string : 1} Set of type names (used during parsing)
1390
+ # included_files [string] Cython sources included with 'include'
1391
+ # pxd_file_loaded boolean Corresponding .pxd file has been processed
1392
+ # cimported_modules [ModuleScope] Modules imported with cimport
1393
+ # types_imported {PyrexType} Set of types for which import code generated
1394
+ # has_import_star boolean Module contains import *
1395
+ # cpp boolean Compiling a C++ file
1396
+ # is_cython_builtin boolean Is this the Cython builtin scope (or a child scope)
1397
+ # is_package boolean Is this a package module? (__init__)
1398
+
1399
+ is_module_scope = 1
1400
+ has_import_star = 0
1401
+ is_cython_builtin = 0
1402
+ old_style_globals = 0
1403
+ cpp = False
1404
+ namespace_cname_is_type = False
1405
+ scope_predefined_names = [
1406
+ '__builtins__', '__name__', '__file__', '__doc__', '__path__',
1407
+ '__spec__', '__loader__', '__package__', '__cached__',
1408
+ ]
1409
+
1410
+ def __init__(self, name, parent_module, context, is_package=False):
1411
+ from . import Builtin
1412
+ self.parent_module = parent_module
1413
+ outer_scope = Builtin.builtin_scope
1414
+ Scope.__init__(self, name, outer_scope, parent_module)
1415
+ self.is_package = is_package
1416
+ self.module_name = EncodedString(name)
1417
+ self._context = context
1418
+ self.module_cname = Naming.module_cname
1419
+ self.module_dict_cname = Naming.moddict_cname
1420
+ self.method_table_cname = Naming.methtable_cname
1421
+ self.doc = ""
1422
+ self.doc_cname = Naming.moddoc_cname
1423
+ self.utility_code_list = []
1424
+ self.module_entries = {}
1425
+ self.c_includes = {}
1426
+ self.type_names = dict(outer_scope.type_names)
1427
+ self.pxd_file_loaded = 0
1428
+ self.cimported_modules = []
1429
+ self.types_imported = set()
1430
+ self.included_files = []
1431
+ self.has_extern_class = 0
1432
+ self.cached_builtins = []
1433
+ self.undeclared_cached_builtins = []
1434
+ self.namespace_cname = self.module_cname
1435
+ self._cached_tuple_types = {}
1436
+ self._cached_defaults_c_class_entries = {}
1437
+ self.process_include(Code.IncludeCode("Python.h", initial=True))
1438
+
1439
+ def qualifying_scope(self):
1440
+ return self.parent_module
1441
+
1442
+ @property
1443
+ def context(self):
1444
+ return self._context
1445
+
1446
+ def global_scope(self):
1447
+ return self
1448
+
1449
+ def lookup(self, name, language_level=None):
1450
+ entry = self.lookup_here(name)
1451
+ if entry is not None:
1452
+ return entry
1453
+
1454
+ if language_level is None:
1455
+ language_level = self.context.language_level if self.context is not None else 3
1456
+ return self.outer_scope.lookup(name, language_level=language_level)
1457
+
1458
+ def declare_tuple_type(self, pos, components):
1459
+ components = tuple(components)
1460
+ try:
1461
+ ttype = self._cached_tuple_types[components]
1462
+ except KeyError:
1463
+ ttype = self._cached_tuple_types[components] = PyrexTypes.c_tuple_type(components)
1464
+ cname = ttype.cname
1465
+ entry = self.lookup_here(cname)
1466
+ if not entry:
1467
+ scope = StructOrUnionScope(cname)
1468
+ for ix, component in enumerate(components):
1469
+ scope.declare_var(name="f%s" % ix, type=component, pos=pos)
1470
+ struct_entry = self.declare_struct_or_union(
1471
+ cname + '_struct', 'struct', scope, typedef_flag=True, pos=pos, cname=cname)
1472
+ self.type_entries.remove(struct_entry)
1473
+ ttype.struct_entry = struct_entry
1474
+ entry = self.declare_type(cname, ttype, pos, cname)
1475
+ ttype.entry = entry
1476
+ return entry
1477
+
1478
+ def declare_defaults_c_class(self, pos, components):
1479
+ # returns an entry (for the c-class)
1480
+ components = tuple(components)
1481
+ try:
1482
+ return self._cached_defaults_c_class_entries[components]
1483
+ except KeyError:
1484
+ pass
1485
+
1486
+ cname = self.next_id(Naming.defaults_struct_prefix)
1487
+ cname = EncodedString(cname)
1488
+ entry = self._cached_defaults_c_class_entries[components] = self.declare_c_class(
1489
+ cname, pos, defining=True, implementing=True,
1490
+ objstruct_cname=cname)
1491
+ self.check_c_class(entry)
1492
+ entry.type.is_final_type = True
1493
+ scope = entry.type.scope
1494
+ scope.is_internal = True
1495
+ scope.is_defaults_class_scope = True
1496
+
1497
+ # zero pad the argument number so they can be sorted
1498
+ num_zeros = len(str(len(components)))
1499
+ build_argname = ("arg{:0>%dd}" % num_zeros).format
1500
+ for n, type_ in enumerate(components):
1501
+ arg_name = EncodedString(build_argname(n))
1502
+ scope.declare_var(arg_name, type_, pos=None, is_cdef=True)
1503
+ return entry
1504
+
1505
+ def declare_builtin(self, name, pos):
1506
+ if name not in PyrexTypes.KNOWN_PYTHON_BUILTINS \
1507
+ and name not in Code.renamed_py2_builtins_map \
1508
+ and name not in PyrexTypes.uncachable_builtins:
1509
+ if self.has_import_star:
1510
+ entry = self.declare_var(name, py_object_type, pos)
1511
+ return entry
1512
+ else:
1513
+ if Options.error_on_unknown_names:
1514
+ error(pos, "undeclared name not builtin: %s" % name)
1515
+ else:
1516
+ warning(pos, "undeclared name not builtin: %s" % name, 2)
1517
+ # unknown - assume it's builtin and look it up at runtime
1518
+ entry = self.declare(name, None, py_object_type, pos, 'private')
1519
+ entry.is_builtin = 1
1520
+ return entry
1521
+ if Options.cache_builtins:
1522
+ for entry in self.cached_builtins:
1523
+ if entry.name == name:
1524
+ return entry
1525
+ if name == 'globals' and not self.old_style_globals:
1526
+ return self.outer_scope.lookup('__Pyx_Globals')
1527
+ else:
1528
+ entry = self.declare(None, None, py_object_type, pos, 'private')
1529
+ if Options.cache_builtins and name not in PyrexTypes.uncachable_builtins:
1530
+ entry.is_builtin = 1
1531
+ entry.is_const = 1 # cached
1532
+ entry.name = name
1533
+ entry.cname = Naming.builtin_prefix + name
1534
+ self.cached_builtins.append(entry)
1535
+ self.undeclared_cached_builtins.append(entry)
1536
+ else:
1537
+ entry.is_builtin = 1
1538
+ entry.name = name
1539
+ entry.qualified_name = self.builtin_scope().qualify_name(name)
1540
+ return entry
1541
+
1542
+ def find_module(self, module_name, pos, relative_level=-1):
1543
+ # Find a module in the import namespace, interpreting
1544
+ # relative imports relative to this module's parent.
1545
+ # Finds and parses the module's .pxd file if the module
1546
+ # has not been referenced before.
1547
+ is_relative_import = relative_level is not None and relative_level > 0
1548
+ from_module = None
1549
+ absolute_fallback = False
1550
+ if relative_level is not None and relative_level > 0:
1551
+ # explicit relative cimport
1552
+ # error of going beyond top-level is handled in cimport node
1553
+ from_module = self
1554
+
1555
+ top_level = 1 if self.is_package else 0
1556
+ # * top_level == 1 when file is __init__.pyx, current package (from_module) is the current module
1557
+ # i.e. dot in `from . import ...` points to the current package
1558
+ # * top_level == 0 when file is regular module, current package (from_module) is parent module
1559
+ # i.e. dot in `from . import ...` points to the package where module is placed
1560
+ while relative_level > top_level and from_module:
1561
+ from_module = from_module.parent_module
1562
+ relative_level -= 1
1563
+
1564
+ elif relative_level != 0:
1565
+ # -1 or None: try relative cimport first, then absolute
1566
+ from_module = self.parent_module
1567
+ absolute_fallback = True
1568
+
1569
+ module_scope = self.global_scope()
1570
+ return module_scope.context.find_module(
1571
+ module_name, from_module=from_module, pos=pos, absolute_fallback=absolute_fallback, relative_import=is_relative_import)
1572
+
1573
+ def find_submodule(self, name, as_package=False):
1574
+ # Find and return scope for a submodule of this module,
1575
+ # creating a new empty one if necessary. Doesn't parse .pxd.
1576
+ if '.' in name:
1577
+ name, submodule = name.split('.', 1)
1578
+ else:
1579
+ submodule = None
1580
+ scope = self.lookup_submodule(name)
1581
+ if not scope:
1582
+ scope = ModuleScope(name, parent_module=self, context=self.context, is_package=True if submodule else as_package)
1583
+ self.module_entries[name] = scope
1584
+ if submodule:
1585
+ scope = scope.find_submodule(submodule, as_package=as_package)
1586
+ return scope
1587
+
1588
+ def lookup_submodule(self, name):
1589
+ # Return scope for submodule of this module, or None.
1590
+ if '.' in name:
1591
+ name, submodule = name.split('.', 1)
1592
+ else:
1593
+ submodule = None
1594
+ module = self.module_entries.get(name, None)
1595
+ if submodule and module is not None:
1596
+ module = module.lookup_submodule(submodule)
1597
+ return module
1598
+
1599
+ def add_include_file(self, filename, verbatim_include=None, late=False):
1600
+ """
1601
+ Add `filename` as include file. Add `verbatim_include` as
1602
+ verbatim text in the C file.
1603
+ Both `filename` and `verbatim_include` can be `None` or empty.
1604
+ """
1605
+ inc = Code.IncludeCode(filename, verbatim_include, late=late)
1606
+ self.process_include(inc)
1607
+
1608
+ def process_include(self, inc):
1609
+ """
1610
+ Add `inc`, which is an instance of `IncludeCode`, to this
1611
+ `ModuleScope`. This either adds a new element to the
1612
+ `c_includes` dict or it updates an existing entry.
1613
+
1614
+ In detail: the values of the dict `self.c_includes` are
1615
+ instances of `IncludeCode` containing the code to be put in the
1616
+ generated C file. The keys of the dict are needed to ensure
1617
+ uniqueness in two ways: if an include file is specified in
1618
+ multiple "cdef extern" blocks, only one `#include` statement is
1619
+ generated. Second, the same include might occur multiple times
1620
+ if we find it through multiple "cimport" paths. So we use the
1621
+ generated code (of the form `#include "header.h"`) as dict key.
1622
+
1623
+ If verbatim code does not belong to any include file (i.e. it
1624
+ was put in a `cdef extern from *` block), then we use a unique
1625
+ dict key: namely, the `sortkey()`.
1626
+
1627
+ One `IncludeCode` object can contain multiple pieces of C code:
1628
+ one optional "main piece" for the include file and several other
1629
+ pieces for the verbatim code. The `IncludeCode.dict_update`
1630
+ method merges the pieces of two different `IncludeCode` objects
1631
+ if needed.
1632
+ """
1633
+ key = inc.mainpiece()
1634
+ if key is None:
1635
+ key = inc.sortkey()
1636
+ inc.dict_update(self.c_includes, key)
1637
+ inc = self.c_includes[key]
1638
+
1639
+ def add_imported_module(self, scope):
1640
+ if scope not in self.cimported_modules:
1641
+ for inc in scope.c_includes.values():
1642
+ self.process_include(inc)
1643
+ self.cimported_modules.append(scope)
1644
+ for m in scope.cimported_modules:
1645
+ self.add_imported_module(m)
1646
+
1647
+ def add_imported_entry(self, name, entry, pos):
1648
+ if entry.is_pyglobal:
1649
+ # Allow cimports to follow imports.
1650
+ entry.is_variable = True
1651
+ if entry not in self.entries:
1652
+ self.entries[name] = entry
1653
+ else:
1654
+ warning(pos, "'%s' redeclared " % name, 0)
1655
+
1656
+ def declare_module(self, name, scope, pos):
1657
+ # Declare a cimported module. This is represented as a
1658
+ # Python module-level variable entry with a module
1659
+ # scope attached to it. Reports an error and returns
1660
+ # None if previously declared as something else.
1661
+ entry = self.lookup_here(name)
1662
+ if entry:
1663
+ if entry.is_pyglobal and entry.as_module is scope:
1664
+ return entry # Already declared as the same module
1665
+ if not (entry.is_pyglobal and not entry.as_module):
1666
+ # SAGE -- I put this here so Pyrex
1667
+ # cimport's work across directories.
1668
+ # Currently it tries to multiply define
1669
+ # every module appearing in an import list.
1670
+ # It shouldn't be an error for a module
1671
+ # name to appear again, and indeed the generated
1672
+ # code compiles fine.
1673
+ return entry
1674
+ else:
1675
+ entry = self.declare_var(name, py_object_type, pos)
1676
+ entry.is_variable = 0
1677
+ entry.as_module = scope
1678
+ self.add_imported_module(scope)
1679
+ return entry
1680
+
1681
+ def declare_var(self, name, type, pos,
1682
+ cname=None, visibility='private',
1683
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None):
1684
+ # Add an entry for a global variable. If it is a Python
1685
+ # object type, and not declared with cdef, it will live
1686
+ # in the module dictionary, otherwise it will be a C
1687
+ # global variable.
1688
+ if visibility not in ('private', 'public', 'extern'):
1689
+ error(pos, "Module-level variable cannot be declared %s" % visibility)
1690
+ self._reject_pytyping_modifiers(pos, pytyping_modifiers, ('typing.Optional',)) # let's allow at least this one
1691
+ if not is_cdef:
1692
+ if type is unspecified_type:
1693
+ type = py_object_type
1694
+ if not (type.is_pyobject and not type.is_extension_type):
1695
+ raise InternalError(
1696
+ "Non-cdef global variable is not a generic Python object")
1697
+ if (is_cdef and visibility != "extern"
1698
+ and self.directives['subinterpreters_compatible'] != "no"):
1699
+ extra_warning = ""
1700
+ pyobject_warning = ""
1701
+ if type.is_pyobject:
1702
+ extra_warning = "\nPython objects should not be shared between interpreters"
1703
+ pyobject_warning = "Python "
1704
+ warning(
1705
+ pos,
1706
+ f"Global cdef {pyobject_warning}variable used with subinterpreter support enabled.\n"
1707
+ "This variable is not currently in the per-interpreter module state "
1708
+ "but this will likely change in future releases." +
1709
+ extra_warning,
1710
+ 2+(1 if extra_warning else 0))
1711
+
1712
+ if not cname:
1713
+ defining = not in_pxd
1714
+ if visibility == 'extern' or (visibility == 'public' and defining):
1715
+ cname = name
1716
+ else:
1717
+ cname = self.mangle(Naming.var_prefix, name)
1718
+
1719
+ entry = self.lookup_here(name)
1720
+ if entry and entry.defined_in_pxd:
1721
+ #if visibility != 'private' and visibility != entry.visibility:
1722
+ # warning(pos, "Variable '%s' previously declared as '%s'" % (name, entry.visibility), 1)
1723
+ if not entry.type.same_as(type):
1724
+ if visibility == 'extern' and entry.visibility == 'extern':
1725
+ warning(pos, "Variable '%s' type does not match previous declaration" % name, 1)
1726
+ entry.type = type
1727
+ #else:
1728
+ # error(pos, "Variable '%s' type does not match previous declaration" % name)
1729
+ if entry.visibility != "private":
1730
+ mangled_cname = self.mangle(Naming.var_prefix, name)
1731
+ if entry.cname == mangled_cname:
1732
+ cname = name
1733
+ entry.cname = name
1734
+ if not entry.is_implemented:
1735
+ entry.is_implemented = True
1736
+ return entry
1737
+
1738
+ entry = Scope.declare_var(self, name, type, pos,
1739
+ cname=cname, visibility=visibility,
1740
+ api=api, in_pxd=in_pxd, is_cdef=is_cdef, pytyping_modifiers=pytyping_modifiers)
1741
+ if is_cdef:
1742
+ entry.is_cglobal = 1
1743
+ if entry.type.declaration_value:
1744
+ entry.init = entry.type.declaration_value
1745
+ self.var_entries.append(entry)
1746
+ else:
1747
+ entry.is_pyglobal = 1
1748
+ if Options.cimport_from_pyx:
1749
+ entry.used = 1
1750
+ return entry
1751
+
1752
+ def declare_cfunction(self, name, type, pos,
1753
+ cname=None, visibility='private', api=0, in_pxd=0,
1754
+ defining=0, modifiers=(), utility_code=None, overridable=False):
1755
+ if not defining and 'inline' in modifiers:
1756
+ # TODO(github/1736): Make this an error.
1757
+ warning(pos, "Declarations should not be declared inline.", 1)
1758
+ # Add an entry for a C function.
1759
+ if not cname:
1760
+ if visibility == 'extern' or (visibility == 'public' and defining):
1761
+ cname = name
1762
+ else:
1763
+ cname = self.mangle(Naming.func_prefix, name)
1764
+ if visibility == 'extern' and type.optional_arg_count:
1765
+ error(pos, "Extern functions cannot have default arguments values.")
1766
+ entry = self.lookup_here(name)
1767
+ if entry and entry.defined_in_pxd:
1768
+ if entry.visibility != "private":
1769
+ mangled_cname = self.mangle(Naming.func_prefix, name)
1770
+ if entry.cname == mangled_cname:
1771
+ cname = name
1772
+ entry.cname = cname
1773
+ entry.func_cname = cname
1774
+ entry = Scope.declare_cfunction(
1775
+ self, name, type, pos,
1776
+ cname=cname, visibility=visibility, api=api, in_pxd=in_pxd,
1777
+ defining=defining, modifiers=modifiers, utility_code=utility_code,
1778
+ overridable=overridable)
1779
+ return entry
1780
+
1781
+ def declare_global(self, name, pos):
1782
+ entry = self.lookup_here(name)
1783
+ if not entry:
1784
+ self.declare_var(name, py_object_type, pos)
1785
+
1786
+ def use_utility_code(self, new_code):
1787
+ if new_code is not None:
1788
+ self.utility_code_list.append(new_code)
1789
+
1790
+ def use_entry_utility_code(self, entry):
1791
+ if entry is None:
1792
+ return
1793
+ if entry.utility_code:
1794
+ self.utility_code_list.append(entry.utility_code)
1795
+ if entry.utility_code_definition:
1796
+ self.utility_code_list.append(entry.utility_code_definition)
1797
+ for tp in PyrexTypes.get_all_subtypes(entry.type):
1798
+ if hasattr(tp, "entry") and tp.entry is not entry:
1799
+ self.use_entry_utility_code(tp.entry)
1800
+
1801
+ def declare_c_class(self, name, pos, defining=0, implementing=0,
1802
+ module_name=None, base_type=None, objstruct_cname=None,
1803
+ typeobj_cname=None, typeptr_cname=None, visibility='private',
1804
+ typedef_flag=0, api=0, check_size=None,
1805
+ buffer_defaults=None, shadow=0):
1806
+ # If this is a non-extern typedef class, expose the typedef, but use
1807
+ # the non-typedef struct internally to avoid needing forward
1808
+ # declarations for anonymous structs.
1809
+ if typedef_flag and visibility != 'extern':
1810
+ if not (visibility == 'public' or api):
1811
+ warning(pos, "ctypedef only valid for 'extern' , 'public', and 'api'", 2)
1812
+ objtypedef_cname = objstruct_cname
1813
+ typedef_flag = 0
1814
+ else:
1815
+ objtypedef_cname = None
1816
+ #
1817
+ # Look for previous declaration as a type
1818
+ #
1819
+ entry = self.lookup_here(name)
1820
+ if entry and not shadow:
1821
+ type = entry.type
1822
+ if not (entry.is_type and type.is_extension_type):
1823
+ entry = None # Will cause redeclaration and produce an error
1824
+ else:
1825
+ scope = type.scope
1826
+ if typedef_flag and (not scope or scope.defined):
1827
+ self.check_previous_typedef_flag(entry, typedef_flag, pos)
1828
+ if (scope and scope.defined) or (base_type and type.base_type):
1829
+ if base_type and base_type is not type.base_type:
1830
+ error(pos, "Base type does not match previous declaration")
1831
+ if base_type and not type.base_type:
1832
+ type.base_type = base_type
1833
+ #
1834
+ # Make a new entry if needed
1835
+ #
1836
+ if not entry or shadow:
1837
+ type = PyrexTypes.PyExtensionType(
1838
+ name, typedef_flag, base_type, visibility == 'extern', check_size=check_size)
1839
+ type.pos = pos
1840
+ type.buffer_defaults = buffer_defaults
1841
+ if objtypedef_cname is not None:
1842
+ type.objtypedef_cname = objtypedef_cname
1843
+ if visibility == 'extern':
1844
+ type.module_name = module_name
1845
+ else:
1846
+ type.module_name = self.qualified_name
1847
+ if typeptr_cname:
1848
+ type.typeptr_cname = typeptr_cname
1849
+ else:
1850
+ type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
1851
+ entry = self.declare_type(name, type, pos, visibility = visibility,
1852
+ defining = 0, shadow = shadow)
1853
+ entry.is_cclass = True
1854
+ if objstruct_cname:
1855
+ type.objstruct_cname = objstruct_cname
1856
+ elif not entry.in_cinclude:
1857
+ type.objstruct_cname = self.mangle(Naming.objstruct_prefix, name)
1858
+ else:
1859
+ error(entry.pos,
1860
+ "Object name required for 'public' or 'extern' C class")
1861
+ self.attach_var_entry_to_c_class(entry)
1862
+ self.c_class_entries.append(entry)
1863
+ #
1864
+ # Check for re-definition and create scope if needed
1865
+ #
1866
+ if not type.scope:
1867
+ if defining or implementing:
1868
+ scope = CClassScope(name = name, outer_scope = self,
1869
+ visibility=visibility,
1870
+ parent_type=type)
1871
+ scope.directives = self.directives.copy()
1872
+ if base_type and base_type.scope:
1873
+ scope.declare_inherited_c_attributes(base_type.scope)
1874
+ type.set_scope(scope)
1875
+ self.type_entries.append(entry)
1876
+ else:
1877
+ if defining and type.scope.defined:
1878
+ error(pos, "C class '%s' already defined" % name)
1879
+ elif implementing and type.scope.implemented:
1880
+ error(pos, "C class '%s' already implemented" % name)
1881
+ #
1882
+ # Fill in options, checking for compatibility with any previous declaration
1883
+ #
1884
+ if defining:
1885
+ entry.defined_in_pxd = 1
1886
+ if implementing: # So that filenames in runtime exceptions refer to
1887
+ entry.pos = pos # the .pyx file and not the .pxd file
1888
+ if visibility != 'private' and entry.visibility != visibility:
1889
+ error(pos, "Class '%s' previously declared as '%s'"
1890
+ % (name, entry.visibility))
1891
+ if api:
1892
+ entry.api = 1
1893
+ if objstruct_cname:
1894
+ if type.objstruct_cname and type.objstruct_cname != objstruct_cname:
1895
+ error(pos, "Object struct name differs from previous declaration")
1896
+ type.objstruct_cname = objstruct_cname
1897
+ if typeobj_cname:
1898
+ if type.typeobj_cname and type.typeobj_cname != typeobj_cname:
1899
+ error(pos, "Type object name differs from previous declaration")
1900
+ type.typeobj_cname = typeobj_cname
1901
+
1902
+ if self.directives.get('final'):
1903
+ entry.type.is_final_type = True
1904
+ collection_type = self.directives.get('collection_type')
1905
+ if collection_type == 'sequence':
1906
+ entry.type.has_sequence_flag = True
1907
+ elif collection_type == 'mapping':
1908
+ entry.type.has_mapping_flag = True
1909
+
1910
+ # cdef classes are always exported, but we need to set it to
1911
+ # distinguish between unused Cython utility code extension classes
1912
+ entry.used = True
1913
+
1914
+ #
1915
+ # Return new or existing entry
1916
+ #
1917
+ return entry
1918
+
1919
+ def allocate_vtable_names(self, entry):
1920
+ # If extension type has a vtable, allocate vtable struct and
1921
+ # slot names for it.
1922
+ type = entry.type
1923
+ if type.base_type and type.base_type.vtabslot_cname:
1924
+ #print "...allocating vtabslot_cname because base type has one" ###
1925
+ type.vtabslot_cname = "%s.%s" % (
1926
+ Naming.obj_base_cname, type.base_type.vtabslot_cname)
1927
+ elif type.scope and type.scope.cfunc_entries:
1928
+ # one special case here: when inheriting from builtin
1929
+ # types, the methods may also be built-in, in which
1930
+ # case they won't need a vtable
1931
+ entry_count = len(type.scope.cfunc_entries)
1932
+ base_type = type.base_type
1933
+ while base_type:
1934
+ # FIXME: this will break if we ever get non-inherited C methods
1935
+ if not base_type.scope or entry_count > len(base_type.scope.cfunc_entries):
1936
+ break
1937
+ if base_type.is_builtin_type:
1938
+ # builtin base type defines all methods => no vtable needed
1939
+ return
1940
+ base_type = base_type.base_type
1941
+ #print "...allocating vtabslot_cname because there are C methods" ###
1942
+ type.vtabslot_cname = Naming.vtabslot_cname
1943
+ if type.vtabslot_cname:
1944
+ #print "...allocating other vtable related cnames" ###
1945
+ type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name)
1946
+ type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name)
1947
+
1948
+ def check_c_classes_pxd(self):
1949
+ # Performs post-analysis checking and finishing up of extension types
1950
+ # being implemented in this module. This is called only for the .pxd.
1951
+ #
1952
+ # Checks all extension types declared in this scope to
1953
+ # make sure that:
1954
+ #
1955
+ # * The extension type is fully declared
1956
+ #
1957
+ # Also allocates a name for the vtable if needed.
1958
+ #
1959
+ for entry in self.c_class_entries:
1960
+ # Check defined
1961
+ if not entry.type.scope:
1962
+ error(entry.pos, "C class '%s' is declared but not defined" % entry.name)
1963
+
1964
+ def check_c_class(self, entry):
1965
+ type = entry.type
1966
+ name = entry.name
1967
+ visibility = entry.visibility
1968
+ # Check defined
1969
+ if not type.scope:
1970
+ error(entry.pos, "C class '%s' is declared but not defined" % name)
1971
+ # Generate typeobj_cname
1972
+ if visibility != 'extern' and not type.typeobj_cname:
1973
+ type.typeobj_cname = self.mangle(Naming.typeobj_prefix, name)
1974
+ ## Generate typeptr_cname
1975
+ #type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
1976
+ # Check C methods defined
1977
+ if type.scope:
1978
+ for method_entry in type.scope.cfunc_entries:
1979
+ if not method_entry.is_inherited and not method_entry.func_cname:
1980
+ error(method_entry.pos, "C method '%s' is declared but not defined" %
1981
+ method_entry.name)
1982
+ # Allocate vtable name if necessary
1983
+ if type.vtabslot_cname:
1984
+ #print "ModuleScope.check_c_classes: allocating vtable cname for", self ###
1985
+ type.vtable_cname = self.mangle(Naming.vtable_prefix, entry.name)
1986
+
1987
+ def check_c_classes(self):
1988
+ # Performs post-analysis checking and finishing up of extension types
1989
+ # being implemented in this module. This is called only for the main
1990
+ # .pyx file scope, not for cimported .pxd scopes.
1991
+ #
1992
+ # Checks all extension types declared in this scope to
1993
+ # make sure that:
1994
+ #
1995
+ # * The extension type is implemented
1996
+ # * All required object and type names have been specified or generated
1997
+ # * All non-inherited C methods are implemented
1998
+ #
1999
+ # Also allocates a name for the vtable if needed.
2000
+ #
2001
+ debug_check_c_classes = 0
2002
+ if debug_check_c_classes:
2003
+ print("Scope.check_c_classes: checking scope " + self.qualified_name)
2004
+ for entry in self.c_class_entries:
2005
+ if debug_check_c_classes:
2006
+ print("...entry %s %s" % (entry.name, entry))
2007
+ print("......type = ", entry.type)
2008
+ print("......visibility = ", entry.visibility)
2009
+ self.check_c_class(entry)
2010
+
2011
+ def check_c_functions(self):
2012
+ # Performs post-analysis checking making sure all
2013
+ # defined c functions are actually implemented.
2014
+ for name, entry in self.entries.items():
2015
+ if entry.is_cfunction:
2016
+ if (entry.defined_in_pxd
2017
+ and entry.scope is self
2018
+ and entry.visibility != 'extern'
2019
+ and not entry.in_cinclude
2020
+ and not entry.is_implemented):
2021
+ error(entry.pos, "Non-extern C function '%s' declared but not defined" % name)
2022
+
2023
+ def attach_var_entry_to_c_class(self, entry):
2024
+ # The name of an extension class has to serve as both a type
2025
+ # name and a variable name holding the type object. It is
2026
+ # represented in the symbol table by a type entry with a
2027
+ # variable entry attached to it. For the variable entry,
2028
+ # we use a read-only C global variable whose name is an
2029
+ # expression that refers to the type object.
2030
+ from . import Builtin
2031
+ var_entry = Entry(name = entry.name,
2032
+ type = Builtin.type_type,
2033
+ pos = entry.pos,
2034
+ cname = entry.type.typeptr_cname)
2035
+ var_entry.qualified_name = entry.qualified_name
2036
+ var_entry.is_variable = 1
2037
+ var_entry.is_cglobal = 1
2038
+ var_entry.is_readonly = 1
2039
+ var_entry.is_cclass_var_entry = True
2040
+ var_entry.scope = entry.scope
2041
+ entry.as_variable = var_entry
2042
+
2043
+ def is_cpp(self):
2044
+ return self.cpp
2045
+
2046
+ def infer_types(self):
2047
+ from .TypeInference import PyObjectTypeInferer
2048
+ PyObjectTypeInferer().infer_types(self)
2049
+
2050
+
2051
+ class LocalScope(Scope):
2052
+ is_local_scope = True
2053
+
2054
+ # Does the function have a 'with gil:' block?
2055
+ has_with_gil_block = False
2056
+
2057
+ # Transient attribute, used for symbol table variable declarations
2058
+ _in_with_gil_block = False
2059
+
2060
+ def __init__(self, name, outer_scope, parent_scope = None):
2061
+ if parent_scope is None:
2062
+ parent_scope = outer_scope
2063
+ Scope.__init__(self, name, outer_scope, parent_scope)
2064
+
2065
+ def mangle(self, prefix, name):
2066
+ return punycodify_name(prefix + name)
2067
+
2068
+ def declare_arg(self, name, type, pos):
2069
+ # Add an entry for an argument of a function.
2070
+ name = self.mangle_class_private_name(name)
2071
+ cname = self.mangle(Naming.var_prefix, name)
2072
+ entry = self.declare(name, cname, type, pos, 'private')
2073
+ entry.is_variable = 1
2074
+ if type.is_pyobject:
2075
+ entry.init = "0"
2076
+ entry.is_arg = 1
2077
+ #entry.borrowed = 1 # Not using borrowed arg refs for now
2078
+ self.arg_entries.append(entry)
2079
+ return entry
2080
+
2081
+ def declare_var(self, name, type, pos,
2082
+ cname=None, visibility='private',
2083
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None):
2084
+ name = self.mangle_class_private_name(name)
2085
+ # Add an entry for a local variable.
2086
+ if visibility in ('public', 'readonly'):
2087
+ error(pos, "Local variable cannot be declared %s" % visibility)
2088
+ entry = Scope.declare_var(self, name, type, pos,
2089
+ cname=cname, visibility=visibility,
2090
+ api=api, in_pxd=in_pxd, is_cdef=is_cdef, pytyping_modifiers=pytyping_modifiers)
2091
+ if entry.type.declaration_value:
2092
+ entry.init = entry.type.declaration_value
2093
+ entry.is_local = 1
2094
+
2095
+ entry.in_with_gil_block = self._in_with_gil_block
2096
+ self.var_entries.append(entry)
2097
+ return entry
2098
+
2099
+ def declare_global(self, name, pos):
2100
+ # Pull entry from global scope into local scope.
2101
+ if self.lookup_here(name):
2102
+ warning(pos, "'%s' redeclared ", 0)
2103
+ else:
2104
+ entry = self.global_scope().lookup_target(name)
2105
+ self.entries[name] = entry
2106
+
2107
+ def declare_nonlocal(self, name, pos):
2108
+ # Pull entry from outer scope into local scope
2109
+ orig_entry = self.lookup_here(name)
2110
+ if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
2111
+ error(pos, "'%s' redeclared as nonlocal" % name)
2112
+ orig_entry.already_declared_here()
2113
+ else:
2114
+ entry = self.lookup(name)
2115
+ if entry is None or not entry.from_closure:
2116
+ error(pos, "no binding for nonlocal '%s' found" % name)
2117
+
2118
+ def _create_inner_entry_for_closure(self, name, entry):
2119
+ entry.in_closure = True
2120
+ inner_entry = InnerEntry(entry, self)
2121
+ inner_entry.is_variable = True
2122
+ self.entries[name] = inner_entry
2123
+ return inner_entry
2124
+
2125
+ def lookup(self, name):
2126
+ # Look up name in this scope or an enclosing one.
2127
+ # Return None if not found.
2128
+
2129
+ entry = Scope.lookup(self, name)
2130
+ if entry is not None:
2131
+ entry_scope = entry.scope
2132
+ while entry_scope.is_comprehension_scope:
2133
+ entry_scope = entry_scope.outer_scope
2134
+ if entry_scope is not self and entry_scope.is_closure_scope:
2135
+ if hasattr(entry.scope, "scope_class"):
2136
+ raise InternalError("lookup() after scope class created.")
2137
+ # The actual c fragment for the different scopes differs
2138
+ # on the outside and inside, so we make a new entry
2139
+ return self._create_inner_entry_for_closure(name, entry)
2140
+ return entry
2141
+
2142
+ def mangle_closure_cnames(self, outer_scope_cname):
2143
+ for scope in self.iter_local_scopes():
2144
+ for entry in scope.entries.values():
2145
+ if entry.from_closure:
2146
+ cname = entry.outer_entry.cname
2147
+ if self.is_passthrough:
2148
+ entry.cname = cname
2149
+ else:
2150
+ if cname.startswith(Naming.cur_scope_cname):
2151
+ cname = cname[len(Naming.cur_scope_cname)+2:]
2152
+ entry.cname = "%s->%s" % (outer_scope_cname, cname)
2153
+ elif entry.in_closure:
2154
+ entry.original_cname = entry.cname
2155
+ entry.cname = "%s->%s" % (Naming.cur_scope_cname, entry.cname)
2156
+ if entry.type.is_cpp_class and entry.scope.directives['cpp_locals']:
2157
+ entry.make_cpp_optional()
2158
+
2159
+
2160
+ class ComprehensionScope(Scope):
2161
+ """Scope for comprehensions (but not generator expressions, which use ClosureScope).
2162
+ As opposed to generators, these can be easily inlined in some cases, so all
2163
+ we really need is a scope that holds the loop variable(s).
2164
+ """
2165
+ is_comprehension_scope = True
2166
+
2167
+ def __init__(self, outer_scope):
2168
+ parent_scope = outer_scope
2169
+ # TODO: also ignore class scopes?
2170
+ while parent_scope.is_comprehension_scope:
2171
+ parent_scope = parent_scope.parent_scope
2172
+ name = parent_scope.global_scope().next_id(Naming.genexpr_id_ref)
2173
+ Scope.__init__(self, name, outer_scope, parent_scope)
2174
+ self.directives = outer_scope.directives
2175
+ self.genexp_prefix = "%s%d%s" % (Naming.pyrex_prefix, len(name), name)
2176
+
2177
+ # Class/ExtType scopes are filled at class creation time, i.e. from the
2178
+ # module init function or surrounding function.
2179
+ while outer_scope.is_comprehension_scope or outer_scope.is_c_class_scope or outer_scope.is_py_class_scope:
2180
+ outer_scope = outer_scope.outer_scope
2181
+ self.var_entries = outer_scope.var_entries # keep declarations outside
2182
+ outer_scope.subscopes.add(self)
2183
+
2184
+ def mangle(self, prefix, name):
2185
+ return '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(prefix, name))
2186
+
2187
+ def declare_var(self, name, type, pos,
2188
+ cname=None, visibility='private',
2189
+ api=False, in_pxd=False, is_cdef=True, pytyping_modifiers=None):
2190
+ if type is unspecified_type:
2191
+ # if the outer scope defines a type for this variable, inherit it
2192
+ outer_entry = self.outer_scope.lookup(name)
2193
+ if outer_entry and outer_entry.is_variable:
2194
+ type = outer_entry.type # may still be 'unspecified_type' !
2195
+ self._reject_pytyping_modifiers(pos, pytyping_modifiers)
2196
+ # the parent scope needs to generate code for the variable, but
2197
+ # this scope must hold its name exclusively
2198
+ cname = '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(Naming.var_prefix, name or self.next_id()))
2199
+ entry = self.declare(name, cname, type, pos, visibility)
2200
+ entry.is_variable = True
2201
+ if self.parent_scope.is_module_scope:
2202
+ entry.is_cglobal = True
2203
+ else:
2204
+ entry.is_local = True
2205
+ entry.in_subscope = True
2206
+ self.var_entries.append(entry)
2207
+ self.entries[name] = entry
2208
+ return entry
2209
+
2210
+ def declare_assignment_expression_target(self, name, type, pos):
2211
+ # should be declared in the parent scope instead
2212
+ return self.parent_scope.declare_var(name, type, pos)
2213
+
2214
+ def declare_pyfunction(self, name, pos, allow_redefine=False):
2215
+ return self.outer_scope.declare_pyfunction(
2216
+ name, pos, allow_redefine)
2217
+
2218
+ def declare_lambda_function(self, func_cname, pos):
2219
+ return self.outer_scope.declare_lambda_function(func_cname, pos)
2220
+
2221
+ def add_lambda_def(self, def_node):
2222
+ return self.outer_scope.add_lambda_def(def_node)
2223
+
2224
+ def lookup_assignment_expression_target(self, name):
2225
+ entry = self.lookup_here(name)
2226
+ if not entry:
2227
+ entry = self.parent_scope.lookup_assignment_expression_target(name)
2228
+ return entry
2229
+
2230
+
2231
+ class ClosureScope(LocalScope):
2232
+
2233
+ is_closure_scope = True
2234
+ is_pure_generator_scope = False
2235
+
2236
+ def __init__(self, name, scope_name, outer_scope, parent_scope=None,
2237
+ is_pure_generator_scope=False):
2238
+ LocalScope.__init__(self, name, outer_scope, parent_scope)
2239
+ self.is_pure_generator_scope = is_pure_generator_scope
2240
+ self.closure_cname = "%s%s" % (Naming.closure_scope_prefix, scope_name)
2241
+
2242
+ # def mangle_closure_cnames(self, scope_var):
2243
+ # for entry in self.entries.values() + self.temp_entries:
2244
+ # entry.in_closure = 1
2245
+ # LocalScope.mangle_closure_cnames(self, scope_var)
2246
+
2247
+ # def mangle(self, prefix, name):
2248
+ # return "%s->%s" % (self.cur_scope_cname, name)
2249
+ # return "%s->%s" % (self.closure_cname, name)
2250
+
2251
+ def declare_pyfunction(self, name, pos, allow_redefine=False):
2252
+ return LocalScope.declare_pyfunction(self, name, pos, allow_redefine, visibility='private')
2253
+
2254
+ def declare_assignment_expression_target(self, name, type, pos):
2255
+ return self.declare_var(name, type, pos)
2256
+
2257
+
2258
+ class GeneratorExpressionScope(ClosureScope):
2259
+ is_generator_expression_scope = True
2260
+
2261
+ def declare_assignment_expression_target(self, name, type, pos):
2262
+ entry = self.parent_scope.declare_var(name, type, pos)
2263
+ return self._create_inner_entry_for_closure(name, entry)
2264
+
2265
+ def lookup_assignment_expression_target(self, name):
2266
+ entry = self.lookup_here(name)
2267
+ if not entry:
2268
+ entry = self.parent_scope.lookup_assignment_expression_target(name)
2269
+ if entry:
2270
+ return self._create_inner_entry_for_closure(name, entry)
2271
+ return entry
2272
+
2273
+
2274
+ class StructOrUnionScope(Scope):
2275
+ # Namespace of a C struct or union.
2276
+
2277
+ def __init__(self, name="?"):
2278
+ Scope.__init__(self, name, outer_scope=None, parent_scope=None)
2279
+
2280
+ def declare_var(self, name, type, pos,
2281
+ cname=None, visibility='private',
2282
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None,
2283
+ allow_pyobject=False, allow_memoryview=False, allow_refcounted=False):
2284
+ # Add an entry for an attribute.
2285
+ if not cname:
2286
+ cname = name
2287
+ if visibility == 'private':
2288
+ cname = c_safe_identifier(cname)
2289
+ if type.is_cfunction:
2290
+ type = PyrexTypes.CPtrType(type)
2291
+ self._reject_pytyping_modifiers(pos, pytyping_modifiers)
2292
+ entry = self.declare(name, cname, type, pos, visibility)
2293
+ entry.is_variable = 1
2294
+ self.var_entries.append(entry)
2295
+ if type.is_pyobject:
2296
+ if not allow_pyobject:
2297
+ error(pos, "C struct/union member cannot be a Python object")
2298
+ elif type.is_memoryviewslice:
2299
+ if not allow_memoryview:
2300
+ # Memory views wrap their buffer owner as a Python object.
2301
+ error(pos, "C struct/union member cannot be a memory view")
2302
+ elif type.needs_refcounting:
2303
+ if not allow_refcounted:
2304
+ error(pos, "C struct/union member cannot be reference-counted type '%s'" % type)
2305
+ return entry
2306
+
2307
+ def declare_cfunction(self, name, type, pos,
2308
+ cname=None, visibility='private', api=0, in_pxd=0,
2309
+ defining=0, modifiers=(), overridable=False): # currently no utility code ...
2310
+ if overridable:
2311
+ error(pos, "C struct/union member cannot be declared 'cpdef'")
2312
+ return self.declare_var(name, type, pos,
2313
+ cname=cname, visibility=visibility)
2314
+
2315
+
2316
+ class ClassScope(Scope):
2317
+ # Abstract base class for namespace of
2318
+ # Python class or extension type.
2319
+ #
2320
+ # class_name string Python name of the class
2321
+ # scope_prefix string Additional prefix for names
2322
+ # declared in the class
2323
+ # doc string or None Doc string
2324
+
2325
+ scope_predefined_names = ['__module__', '__qualname__']
2326
+
2327
+ def mangle_class_private_name(self, name):
2328
+ # a few utilitycode names need to specifically be ignored
2329
+ if name and name.lower().startswith("__pyx_"):
2330
+ return name
2331
+ if name and name.startswith('__') and not name.endswith('__'):
2332
+ name = EncodedString('_%s%s' % (self.class_name.lstrip('_'), name))
2333
+ return name
2334
+
2335
+ def __init__(self, name, outer_scope):
2336
+ Scope.__init__(self, name, outer_scope, outer_scope)
2337
+ self.class_name = name
2338
+ self.doc = None
2339
+
2340
+ def lookup(self, name):
2341
+ entry = Scope.lookup(self, name)
2342
+ if entry:
2343
+ return entry
2344
+ if name == "classmethod":
2345
+ # We don't want to use the builtin classmethod here 'cause it won't do the
2346
+ # right thing in this scope (as the class members aren't still functions).
2347
+ # Don't want to add a cfunction to this scope 'cause that would mess with
2348
+ # the type definition, so we just return the right entry.
2349
+ entry = Entry(
2350
+ "classmethod",
2351
+ "__Pyx_Method_ClassMethod",
2352
+ PyrexTypes.CFuncType(
2353
+ py_object_type,
2354
+ [PyrexTypes.CFuncTypeArg("", py_object_type, None)], 0, 0))
2355
+ entry.utility_code_definition = Code.UtilityCode.load_cached("ClassMethod", "CythonFunction.c")
2356
+ self.use_entry_utility_code(entry)
2357
+ entry.is_cfunction = 1
2358
+ entry.scope = self.builtin_scope()
2359
+ return entry
2360
+
2361
+
2362
+ class PyClassScope(ClassScope):
2363
+ # Namespace of a Python class.
2364
+
2365
+ is_py_class_scope = 1
2366
+ namespace_cname_is_type = False
2367
+
2368
+ def declare_var(self, name, type, pos,
2369
+ cname=None, visibility='private',
2370
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None):
2371
+ name = self.mangle_class_private_name(name)
2372
+ if type is unspecified_type:
2373
+ type = py_object_type
2374
+ # Add an entry for a class attribute.
2375
+ entry = Scope.declare_var(self, name, type, pos,
2376
+ cname=cname, visibility=visibility,
2377
+ api=api, in_pxd=in_pxd, is_cdef=is_cdef, pytyping_modifiers=pytyping_modifiers)
2378
+ entry.is_pyglobal = 1
2379
+ entry.is_pyclass_attr = 1
2380
+ return entry
2381
+
2382
+ def declare_nonlocal(self, name, pos):
2383
+ # Pull entry from outer scope into local scope
2384
+ orig_entry = self.lookup_here(name)
2385
+ if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
2386
+ error(pos, "'%s' redeclared as nonlocal" % name)
2387
+ orig_entry.already_declared_here()
2388
+ else:
2389
+ entry = self.lookup(name)
2390
+ if entry is None:
2391
+ error(pos, "no binding for nonlocal '%s' found" % name)
2392
+ else:
2393
+ # FIXME: this works, but it's unclear if it's the
2394
+ # right thing to do
2395
+ self.entries[name] = entry
2396
+
2397
+ def declare_global(self, name, pos):
2398
+ # Pull entry from global scope into local scope.
2399
+ if self.lookup_here(name):
2400
+ warning(pos, "'%s' redeclared ", 0)
2401
+ else:
2402
+ entry = self.global_scope().lookup_target(name)
2403
+ self.entries[name] = entry
2404
+
2405
+ def add_default_value(self, type):
2406
+ return self.outer_scope.add_default_value(type)
2407
+
2408
+
2409
+ class CClassScope(ClassScope):
2410
+ # Namespace of an extension type.
2411
+ #
2412
+ # parent_type PyExtensionType
2413
+ # #typeobj_cname string or None
2414
+ # #objstruct_cname string
2415
+ # method_table_cname string
2416
+ # getset_table_cname string
2417
+ # has_pyobject_attrs boolean Any PyObject attributes?
2418
+ # has_memoryview_attrs boolean Any memory view attributes?
2419
+ # has_explicitly_constructable_class_attrs boolean Any attributes that
2420
+ # need an explicit constructor (e.g. C++ class non-pointers)?
2421
+ # has_cyclic_pyobject_attrs boolean Any PyObject attributes that may need GC?
2422
+ # property_entries [Entry]
2423
+ # defined boolean Defined in .pxd file
2424
+ # implemented boolean Defined in .pyx file
2425
+ # inherited_var_entries [Entry] Adapted var entries from base class
2426
+
2427
+ is_c_class_scope = 1
2428
+ is_closure_class_scope = False
2429
+ is_defaults_class_scope = False
2430
+
2431
+ has_pyobject_attrs = False
2432
+ has_memoryview_attrs = False
2433
+ has_explicitly_constructable_attrs = False
2434
+ has_cyclic_pyobject_attrs = False
2435
+ defined = False
2436
+ implemented = False
2437
+
2438
+ def __init__(self, name, outer_scope, visibility, parent_type):
2439
+ ClassScope.__init__(self, name, outer_scope)
2440
+ if visibility != 'extern':
2441
+ self.method_table_cname = outer_scope.mangle(Naming.methtab_prefix, name)
2442
+ self.getset_table_cname = outer_scope.mangle(Naming.gstab_prefix, name)
2443
+ self.property_entries = []
2444
+ self.inherited_var_entries = []
2445
+ self.parent_type = parent_type
2446
+ # Usually parent_type will be an extension type and so the typeptr_cname
2447
+ # can be used to calculate the namespace_cname. Occasionally other types
2448
+ # are used (e.g. numeric/complex types) and in these cases the typeptr
2449
+ # isn't relevant.
2450
+ if ((parent_type.is_builtin_type or parent_type.is_extension_type)
2451
+ and parent_type.typeptr_cname):
2452
+ self.namespace_cname = self.parent_type.typeptr_cname
2453
+ self.namespace_cname_is_type = True
2454
+
2455
+ def needs_gc(self):
2456
+ # If the type or any of its base types have Python-valued
2457
+ # C attributes, then it needs to participate in GC.
2458
+ if self.has_cyclic_pyobject_attrs and not self.directives.get('no_gc', False):
2459
+ return True
2460
+ if self.parent_type.is_external and not self.parent_type.is_builtin_type:
2461
+ # It's impossible to really know - external types are often incomplete.
2462
+ return True
2463
+ base_type = self.parent_type.base_type
2464
+ if base_type and base_type.scope is not None:
2465
+ return base_type.scope.needs_gc()
2466
+ elif self.parent_type.is_builtin_type:
2467
+ return not self.parent_type.is_gc_simple
2468
+ return False
2469
+
2470
+ def needs_trashcan(self):
2471
+ # If the trashcan directive is explicitly set to False,
2472
+ # unconditionally disable the trashcan.
2473
+ directive = self.directives.get('trashcan')
2474
+ if directive is False:
2475
+ return False
2476
+ # If the directive is set to True and the class has Python-valued
2477
+ # C attributes, then it should use the trashcan in tp_dealloc.
2478
+ if directive and self.has_cyclic_pyobject_attrs:
2479
+ return True
2480
+ # Use the trashcan if the base class uses it
2481
+ base_type = self.parent_type.base_type
2482
+ if base_type and base_type.scope is not None:
2483
+ return base_type.scope.needs_trashcan()
2484
+ return self.parent_type.builtin_trashcan
2485
+
2486
+ def needs_tp_clear(self):
2487
+ """
2488
+ Do we need to generate an implementation for the tp_clear slot? Can
2489
+ be disabled to keep references for the __dealloc__ cleanup function.
2490
+ """
2491
+ return self.needs_gc() and not self.directives.get('no_gc_clear', False)
2492
+
2493
+ def may_have_finalize(self):
2494
+ """
2495
+ This covers cases where we definitely have a __del__ function
2496
+ and also cases where one of the base classes could have a __del__
2497
+ function but we don't know.
2498
+ """
2499
+ current_type_scope = self
2500
+ while current_type_scope:
2501
+ del_entry = current_type_scope.lookup_here("__del__")
2502
+ if del_entry and del_entry.is_special:
2503
+ return True
2504
+ if (current_type_scope.parent_type.is_external or not current_type_scope.implemented or
2505
+ current_type_scope.parent_type.multiple_bases):
2506
+ # we don't know if we have __del__, so assume we do and call it
2507
+ return True
2508
+ current_base_type = current_type_scope.parent_type.base_type
2509
+ current_type_scope = current_base_type.scope if current_base_type else None
2510
+ return False
2511
+
2512
+ def get_refcounted_entries(self, include_weakref=False,
2513
+ include_gc_simple=True):
2514
+ py_attrs = []
2515
+ py_buffers = []
2516
+ memoryview_slices = []
2517
+
2518
+ for entry in self.var_entries:
2519
+ if entry.type.is_pyobject:
2520
+ if include_weakref or (self.is_closure_class_scope or entry.name != "__weakref__"):
2521
+ if include_gc_simple or not entry.type.is_gc_simple:
2522
+ py_attrs.append(entry)
2523
+ elif entry.type == PyrexTypes.c_py_buffer_type:
2524
+ py_buffers.append(entry)
2525
+ elif entry.type.is_memoryviewslice:
2526
+ memoryview_slices.append(entry)
2527
+
2528
+ have_entries = py_attrs or py_buffers or memoryview_slices
2529
+ return have_entries, (py_attrs, py_buffers, memoryview_slices)
2530
+
2531
+ def declare_var(self, name, type, pos,
2532
+ cname=None, visibility='private',
2533
+ api=False, in_pxd=False, is_cdef=False, pytyping_modifiers=None):
2534
+ name = self.mangle_class_private_name(name)
2535
+
2536
+ if pytyping_modifiers:
2537
+ if "typing.ClassVar" in pytyping_modifiers:
2538
+ is_cdef = 0
2539
+ if not type.is_pyobject:
2540
+ if not type.equivalent_type:
2541
+ warning(pos, "ClassVar[] requires the type to be a Python object type. Found '%s', using object instead." % type)
2542
+ type = py_object_type
2543
+ else:
2544
+ type = type.equivalent_type
2545
+ if "dataclasses.InitVar" in pytyping_modifiers and not self.is_c_dataclass_scope:
2546
+ error(pos, "Use of cython.dataclasses.InitVar does not make sense outside a dataclass")
2547
+
2548
+ if is_cdef:
2549
+ # Add an entry for an attribute.
2550
+ if self.defined:
2551
+ error(pos,
2552
+ "C attributes cannot be added in implementation part of"
2553
+ " extension type defined in a pxd")
2554
+ if (not self.is_closure_class_scope and
2555
+ get_slot_table(self.directives).get_special_method_signature(name)):
2556
+ error(pos,
2557
+ "The name '%s' is reserved for a special method."
2558
+ % name)
2559
+ if not cname:
2560
+ cname = name
2561
+ if not (self.parent_type.is_external or self.parent_type.entry.api or
2562
+ self.parent_type.entry.visibility == "public"):
2563
+ cname = c_safe_identifier(cname)
2564
+ cname = punycodify_name(cname, Naming.unicode_structmember_prefix)
2565
+ entry = self.declare(name, cname, type, pos, visibility)
2566
+ entry.is_variable = 1
2567
+ self.var_entries.append(entry)
2568
+ entry.pytyping_modifiers = pytyping_modifiers
2569
+ if type.is_cpp_class and visibility != 'extern':
2570
+ if self.directives['cpp_locals']:
2571
+ entry.make_cpp_optional()
2572
+ else:
2573
+ type.check_nullary_constructor(pos)
2574
+ if type.is_memoryviewslice:
2575
+ self.has_memoryview_attrs = True
2576
+ elif type.needs_explicit_construction(self):
2577
+ self.has_explicitly_constructable_attrs = True
2578
+ elif type.is_pyobject and (self.is_closure_class_scope or name != '__weakref__'):
2579
+ self.has_pyobject_attrs = True
2580
+ if (not type.is_builtin_type
2581
+ or not type.scope or type.scope.needs_gc()):
2582
+ self.has_cyclic_pyobject_attrs = True
2583
+ if visibility not in ('private', 'public', 'readonly'):
2584
+ error(pos,
2585
+ "Attribute of extension type cannot be declared %s" % visibility)
2586
+ if visibility in ('public', 'readonly'):
2587
+ # If the field is an external typedef, we cannot be sure about the type,
2588
+ # so do conversion ourself rather than rely on the CPython mechanism (through
2589
+ # a property; made in AnalyseDeclarationsTransform).
2590
+ entry.needs_property = True
2591
+ if not self.is_closure_class_scope and name in ("__dict__", "__weakref__"):
2592
+ error(pos, f"Special attribute {name} cannot be exposed to Python")
2593
+ if not (type.is_pyobject or type.can_coerce_to_pyobject(self)):
2594
+ # we're not testing for coercion *from* Python here - that would fail later
2595
+ error(pos, "C attribute of type '%s' cannot be accessed from Python" % type)
2596
+ else:
2597
+ entry.needs_property = False
2598
+ return entry
2599
+ else:
2600
+ if type is unspecified_type:
2601
+ type = py_object_type
2602
+ # Add an entry for a class attribute.
2603
+ entry = Scope.declare_var(self, name, type, pos,
2604
+ cname=cname, visibility=visibility,
2605
+ api=api, in_pxd=in_pxd, is_cdef=is_cdef, pytyping_modifiers=pytyping_modifiers)
2606
+ entry.is_member = 1
2607
+ # xxx: is_pyglobal changes behaviour in so many places that I keep it in for now.
2608
+ # is_member should be enough later on
2609
+ entry.is_pyglobal = 1
2610
+
2611
+ return entry
2612
+
2613
+ def declare_pyfunction(self, name, pos, allow_redefine=False):
2614
+ # Add an entry for a method.
2615
+ if name in richcmp_special_methods:
2616
+ if self.lookup_here('__richcmp__'):
2617
+ error(pos, "Cannot define both % and __richcmp__" % name)
2618
+ elif name == '__richcmp__':
2619
+ for n in richcmp_special_methods:
2620
+ if self.lookup_here(n):
2621
+ error(pos, "Cannot define both % and __richcmp__" % n)
2622
+ if name == "__new__":
2623
+ error(pos, "__new__ method of extension type will change semantics "
2624
+ "in a future version of Pyrex and Cython. Use __cinit__ instead.")
2625
+ entry = self.declare_var(name, py_object_type, pos,
2626
+ visibility='extern')
2627
+ special_sig = get_slot_table(self.directives).get_special_method_signature(name)
2628
+ if special_sig:
2629
+ # Special methods get put in the method table with a particular
2630
+ # signature declared in advance.
2631
+ entry.signature = special_sig
2632
+ entry.is_special = 1
2633
+ else:
2634
+ entry.signature = pymethod_signature
2635
+ entry.is_special = 0
2636
+
2637
+ self.pyfunc_entries.append(entry)
2638
+ return entry
2639
+
2640
+ def lookup_here(self, name):
2641
+ if not self.is_closure_class_scope and name == "__new__":
2642
+ name = EncodedString("__cinit__")
2643
+ entry = ClassScope.lookup_here(self, name)
2644
+ if entry and entry.is_builtin_cmethod:
2645
+ if not self.parent_type.is_builtin_type:
2646
+ # For subtypes of builtin types, we can only return
2647
+ # optimised C methods if the type if final.
2648
+ # Otherwise, subtypes may choose to override the
2649
+ # method, but the optimisation would prevent the
2650
+ # subtype method from being called.
2651
+ if not self.parent_type.is_final_type:
2652
+ return None
2653
+ return entry
2654
+
2655
+ def declare_cfunction(self, name, type, pos,
2656
+ cname=None, visibility='private', api=0, in_pxd=0,
2657
+ defining=0, modifiers=(), utility_code=None, overridable=False):
2658
+ name = self.mangle_class_private_name(name)
2659
+ if (get_slot_table(self.directives).get_special_method_signature(name)
2660
+ and not self.parent_type.is_builtin_type):
2661
+ error(pos, "Special methods must be declared with 'def', not 'cdef'")
2662
+ args = type.args
2663
+ if not type.is_static_method:
2664
+ if not args:
2665
+ error(pos, "C method has no self argument")
2666
+ elif not self.parent_type.assignable_from(args[0].type):
2667
+ error(pos, "Self argument (%s) of C method '%s' does not match parent type (%s)" %
2668
+ (args[0].type, name, self.parent_type))
2669
+ entry = self.lookup_here(name)
2670
+ if cname is None:
2671
+ cname = punycodify_name(c_safe_identifier(name), Naming.unicode_vtabentry_prefix)
2672
+ if entry:
2673
+ if not entry.is_cfunction:
2674
+ error(pos, "'%s' redeclared " % name)
2675
+ entry.already_declared_here()
2676
+ else:
2677
+ if defining and entry.func_cname:
2678
+ error(pos, "'%s' already defined" % name)
2679
+ #print "CClassScope.declare_cfunction: checking signature" ###
2680
+ if entry.is_final_cmethod and entry.is_inherited:
2681
+ error(pos, "Overriding final methods is not allowed")
2682
+ elif type.same_c_signature_as(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
2683
+ # Fix with_gil vs nogil.
2684
+ entry.type = entry.type.with_with_gil(type.with_gil)
2685
+ elif type.compatible_signature_with(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
2686
+ if (self.defined and not in_pxd
2687
+ and not type.same_c_signature_as_resolved_type(
2688
+ entry.type, as_cmethod=1, as_pxd_definition=1)):
2689
+ # TODO(robertwb): Make this an error.
2690
+ warning(pos,
2691
+ "Compatible but non-identical C method '%s' not redeclared "
2692
+ "in definition part of extension type '%s'. "
2693
+ "This may cause incorrect vtables to be generated." % (
2694
+ name, self.class_name), 2)
2695
+ warning(entry.pos, "Previous declaration is here", 2)
2696
+ entry = self.add_cfunction(name, type, pos, cname, visibility='ignore', modifiers=modifiers)
2697
+ else:
2698
+ error(pos, "Signature not compatible with previous declaration")
2699
+ error(entry.pos, "Previous declaration is here")
2700
+ else:
2701
+ if self.defined:
2702
+ error(pos,
2703
+ "C method '%s' not previously declared in definition part of"
2704
+ " extension type '%s'" % (name, self.class_name))
2705
+ entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
2706
+ if defining:
2707
+ entry.func_cname = self.mangle(Naming.func_prefix, name)
2708
+ entry.utility_code = utility_code
2709
+ type.entry = entry
2710
+
2711
+ if 'inline' in modifiers:
2712
+ entry.is_inline_cmethod = True
2713
+
2714
+ if self.parent_type.is_final_type or entry.is_inline_cmethod or self.directives.get('final'):
2715
+ entry.is_final_cmethod = True
2716
+ entry.final_func_cname = entry.func_cname
2717
+ if not type.is_fused:
2718
+ entry.vtable_type = entry.type
2719
+ entry.type = type
2720
+
2721
+ return entry
2722
+
2723
+ def add_cfunction(self, name, type, pos, cname, visibility, modifiers, inherited=False):
2724
+ # Add a cfunction entry without giving it a func_cname.
2725
+ prev_entry = self.lookup_here(name)
2726
+ entry = ClassScope.add_cfunction(
2727
+ self, name, type, pos, cname, visibility, modifiers, inherited=inherited)
2728
+ entry.is_cmethod = 1
2729
+ entry.prev_entry = prev_entry
2730
+ return entry
2731
+
2732
+ def declare_builtin_cfunction(self, name, type, cname, utility_code = None):
2733
+ # overridden methods of builtin types still have their Python
2734
+ # equivalent that must be accessible to support bound methods
2735
+ name = EncodedString(name)
2736
+ entry = self.declare_cfunction(
2737
+ name, type, pos=None, cname=cname, visibility='extern', utility_code=utility_code)
2738
+ var_entry = Entry(name, name, py_object_type)
2739
+ var_entry.qualified_name = name
2740
+ var_entry.is_variable = 1
2741
+ var_entry.is_builtin = 1
2742
+ var_entry.utility_code = utility_code
2743
+ var_entry.scope = entry.scope
2744
+ entry.as_variable = var_entry
2745
+ return entry
2746
+
2747
+ def declare_property(self, name, doc, pos, ctype=None, property_scope=None):
2748
+ entry = self.lookup_here(name)
2749
+ if entry is None:
2750
+ entry = self.declare(name, name, py_object_type if ctype is None else ctype, pos, 'private')
2751
+ entry.is_property = True
2752
+ if ctype is not None:
2753
+ entry.is_cproperty = True
2754
+ entry.doc = doc
2755
+ if property_scope is None:
2756
+ entry.scope = PropertyScope(name, class_scope=self)
2757
+ else:
2758
+ entry.scope = property_scope
2759
+ self.property_entries.append(entry)
2760
+ return entry
2761
+
2762
+ def declare_cproperty(self, name, type, cfunc_name, setter_cfunc_name=None,
2763
+ doc=None, pos=None, visibility='extern',
2764
+ nogil=False, with_gil=False,
2765
+ exception_value=None, exception_check=False, setter_raises=True,
2766
+ utility_code=None, setter_utility_code=None):
2767
+ """Internal convenience method to declare a C property function in one go.
2768
+ """
2769
+ property_entry = self.declare_property(name, doc=doc, ctype=type, pos=pos)
2770
+ getter_cfunc_entry = property_entry.scope.declare_cfunction(
2771
+ name="__get__",
2772
+ type=PyrexTypes.CFuncType(
2773
+ type,
2774
+ [PyrexTypes.CFuncTypeArg("self", self.parent_type, pos=None)],
2775
+ nogil=nogil,
2776
+ with_gil=with_gil,
2777
+ exception_value=exception_value,
2778
+ exception_check=exception_check,
2779
+ ),
2780
+ cname=cfunc_name,
2781
+ utility_code=utility_code,
2782
+ visibility=visibility,
2783
+ pos=pos,
2784
+ )
2785
+ setter_cfunc_entry = None
2786
+ if setter_cfunc_name:
2787
+ setter_cfunc_entry = property_entry.scope.declare_cfunction(
2788
+ name="__set__",
2789
+ type=PyrexTypes.CFuncType(
2790
+ PyrexTypes.c_returncode_type if setter_raises else PyrexTypes.c_void_type,
2791
+ [PyrexTypes.CFuncTypeArg("self", self.parent_type, pos=None),
2792
+ PyrexTypes.CFuncTypeArg("value", type, pos=None)],
2793
+ nogil=nogil,
2794
+ with_gil=with_gil,
2795
+ exception_value=-1 if setter_raises else None,
2796
+ ),
2797
+ cname=setter_cfunc_name,
2798
+ # Allow getter+setter in one utility code section.
2799
+ utility_code=setter_utility_code or utility_code,
2800
+ visibility=visibility,
2801
+ pos=pos,
2802
+ )
2803
+ return property_entry, getter_cfunc_entry, setter_cfunc_entry
2804
+
2805
+ def declare_inherited_c_attributes(self, base_scope):
2806
+ # Declare entries for all the C attributes of an
2807
+ # inherited type, with cnames modified appropriately
2808
+ # to work with this type.
2809
+ def adapt(cname):
2810
+ return "%s.%s" % (Naming.obj_base_cname, base_entry.cname)
2811
+
2812
+ entries = base_scope.inherited_var_entries + base_scope.var_entries
2813
+ for base_entry in entries:
2814
+ entry = self.declare(
2815
+ base_entry.name, adapt(base_entry.cname),
2816
+ base_entry.type, None, 'private')
2817
+ entry.is_variable = 1
2818
+ entry.is_inherited = True
2819
+ entry.annotation = base_entry.annotation
2820
+ self.inherited_var_entries.append(entry)
2821
+
2822
+ # If the class defined in a pxd, specific entries have not been added.
2823
+ # Ensure now that the parent (base) scope has specific entries
2824
+ # Iterate over a copy as get_all_specialized_function_types() will mutate
2825
+ for base_entry in base_scope.cfunc_entries[:]:
2826
+ if base_entry.type.is_fused:
2827
+ base_entry.type.get_all_specialized_function_types()
2828
+
2829
+ for base_entry in base_scope.cfunc_entries:
2830
+ cname = base_entry.cname
2831
+ var_entry = base_entry.as_variable
2832
+ is_builtin = var_entry and var_entry.is_builtin
2833
+ if not is_builtin:
2834
+ cname = adapt(cname)
2835
+ entry = self.add_cfunction(
2836
+ base_entry.name, base_entry.type, base_entry.pos, cname,
2837
+ base_entry.visibility, base_entry.func_modifiers, inherited=True)
2838
+ entry.is_inherited = 1
2839
+ if base_entry.is_final_cmethod:
2840
+ entry.is_final_cmethod = True
2841
+ entry.is_inline_cmethod = base_entry.is_inline_cmethod
2842
+ if (self.parent_scope == base_scope.parent_scope or
2843
+ entry.is_inline_cmethod):
2844
+ entry.final_func_cname = base_entry.final_func_cname
2845
+ if is_builtin:
2846
+ entry.is_builtin_cmethod = True
2847
+ entry.as_variable = var_entry
2848
+ if base_entry.utility_code:
2849
+ entry.utility_code = base_entry.utility_code
2850
+
2851
+
2852
+ def handle_already_declared_name(self, name, cname, type, pos, visibility, copy_entry=True):
2853
+ # We want to copy the existing entry instead of modifying it, since this is an override.
2854
+ super().handle_already_declared_name(name, cname, type, pos, visibility, copy_entry)
2855
+
2856
+ class CppClassScope(Scope):
2857
+ # Namespace of a C++ class.
2858
+
2859
+ is_cpp_class_scope = 1
2860
+
2861
+ default_constructor = None
2862
+ type = None
2863
+
2864
+ def __init__(self, name, outer_scope, templates=None):
2865
+ Scope.__init__(self, name, outer_scope, None)
2866
+ self.directives = outer_scope.directives
2867
+ self.inherited_var_entries = []
2868
+ if templates is not None:
2869
+ for T in templates:
2870
+ template_entry = self.declare(
2871
+ T, T, PyrexTypes.TemplatePlaceholderType(T), None, 'extern')
2872
+ template_entry.is_type = 1
2873
+
2874
+ def declare_var(self, name, type, pos,
2875
+ cname=None, visibility='extern',
2876
+ api=False, in_pxd=False, is_cdef=False, defining=False, pytyping_modifiers=None):
2877
+ # Add an entry for an attribute.
2878
+ if not cname:
2879
+ cname = name
2880
+ self._reject_pytyping_modifiers(pos, pytyping_modifiers)
2881
+ entry = self.lookup_here(name)
2882
+ if defining and entry is not None:
2883
+ if type.is_cfunction:
2884
+ entry = self.declare(name, cname, type, pos, visibility)
2885
+ elif entry.type.same_as(type):
2886
+ # Fix with_gil vs nogil.
2887
+ entry.type = entry.type.with_with_gil(type.with_gil)
2888
+ else:
2889
+ error(pos, "Function signature does not match previous declaration")
2890
+ else:
2891
+ entry = self.declare(name, cname, type, pos, visibility)
2892
+ if type.is_cfunction and not defining:
2893
+ entry.is_inherited = 1
2894
+ entry.is_variable = 1
2895
+ if type.is_cfunction:
2896
+ entry.is_cfunction = 1
2897
+ if self.type and not self.type.get_fused_types():
2898
+ entry.func_cname = "%s::%s" % (self.type.empty_declaration_code(), cname)
2899
+ if name != "this" and (defining or name != "<init>"):
2900
+ self.var_entries.append(entry)
2901
+ return entry
2902
+
2903
+ def declare_cfunction(self, name, type, pos,
2904
+ cname=None, visibility='extern', api=0, in_pxd=0,
2905
+ defining=0, modifiers=(), utility_code=None, overridable=False):
2906
+ class_name = self.name.split('::')[-1]
2907
+ if name in (class_name, '__init__') and cname is None:
2908
+ cname = "%s__init__%s" % (Naming.func_prefix, class_name)
2909
+ name = EncodedString('<init>')
2910
+ type.return_type = PyrexTypes.CVoidType()
2911
+ # This is called by the actual constructor, but need to support
2912
+ # arguments that cannot by called by value.
2913
+ type.original_args = type.args
2914
+ def maybe_ref(arg):
2915
+ if arg.type.is_cpp_class and not arg.type.is_reference:
2916
+ return PyrexTypes.CFuncTypeArg(
2917
+ arg.name, PyrexTypes.c_ref_type(arg.type), arg.pos)
2918
+ else:
2919
+ return arg
2920
+ type.args = [maybe_ref(arg) for arg in type.args]
2921
+ elif name == '__dealloc__' and cname is None:
2922
+ cname = "%s__dealloc__%s" % (Naming.func_prefix, class_name)
2923
+ name = EncodedString('<del>')
2924
+ type.return_type = PyrexTypes.CVoidType()
2925
+ if name in ('<init>', '<del>') and type.nogil:
2926
+ for base in self.type.base_classes:
2927
+ base_entry = base.scope.lookup(name)
2928
+ if base_entry and not base_entry.type.nogil:
2929
+ error(pos, "Constructor cannot be called without GIL unless all base constructors can also be called without GIL")
2930
+ error(base_entry.pos, "Base constructor defined here.")
2931
+ # The previous entries management is now done directly in Scope.declare
2932
+ entry = self.declare_var(name, type, pos,
2933
+ defining=defining,
2934
+ cname=cname, visibility=visibility)
2935
+ entry.utility_code = utility_code
2936
+ type.entry = entry
2937
+ return entry
2938
+
2939
+ def declare_inherited_cpp_attributes(self, base_class):
2940
+ base_scope = base_class.scope
2941
+ template_type = base_class
2942
+ while getattr(template_type, 'template_type', None):
2943
+ template_type = template_type.template_type
2944
+ if getattr(template_type, 'templates', None):
2945
+ base_templates = [T.name for T in template_type.templates]
2946
+ else:
2947
+ base_templates = ()
2948
+ # Declare entries for all the C++ attributes of an
2949
+ # inherited type, with cnames modified appropriately
2950
+ # to work with this type.
2951
+ for base_entry in base_scope.inherited_var_entries + base_scope.var_entries:
2952
+ #constructor/destructor is not inherited
2953
+ if base_entry.name in ("<init>", "<del>"):
2954
+ continue
2955
+ #print base_entry.name, self.entries
2956
+ if base_entry.name in self.entries:
2957
+ base_entry.name # FIXME: is there anything to do in this case?
2958
+ entry = self.declare(base_entry.name, base_entry.cname,
2959
+ base_entry.type, None, 'extern')
2960
+ entry.is_variable = 1
2961
+ entry.is_inherited = 1
2962
+ if base_entry.is_cfunction:
2963
+ entry.is_cfunction = 1
2964
+ entry.func_cname = base_entry.func_cname
2965
+ self.inherited_var_entries.append(entry)
2966
+ for base_entry in base_scope.cfunc_entries:
2967
+ entry = self.declare_cfunction(base_entry.name, base_entry.type,
2968
+ base_entry.pos, base_entry.cname,
2969
+ base_entry.visibility, api=0,
2970
+ modifiers=base_entry.func_modifiers,
2971
+ utility_code=base_entry.utility_code)
2972
+ entry.is_inherited = 1
2973
+ for base_entry in base_scope.type_entries:
2974
+ if base_entry.name not in base_templates:
2975
+ entry = self.declare_type(base_entry.name, base_entry.type,
2976
+ base_entry.pos, base_entry.cname,
2977
+ base_entry.visibility, defining=False)
2978
+ entry.is_inherited = 1
2979
+
2980
+ def specialize(self, values, type_entry):
2981
+ scope = CppClassScope(self.name, self.outer_scope)
2982
+ scope.type = type_entry
2983
+ for entry in self.entries.values():
2984
+ if entry.is_type:
2985
+ scope.declare_type(entry.name,
2986
+ entry.type.specialize(values),
2987
+ entry.pos,
2988
+ entry.cname,
2989
+ template=1)
2990
+ elif entry.type.is_cfunction:
2991
+ for e in entry.all_alternatives():
2992
+ scope.declare_cfunction(e.name,
2993
+ e.type.specialize(values),
2994
+ e.pos,
2995
+ e.cname,
2996
+ utility_code=e.utility_code)
2997
+ else:
2998
+ scope.declare_var(entry.name,
2999
+ entry.type.specialize(values),
3000
+ entry.pos,
3001
+ entry.cname,
3002
+ entry.visibility)
3003
+
3004
+ return scope
3005
+
3006
+ def lookup_here(self, name):
3007
+ if name == "__init__":
3008
+ name = "<init>"
3009
+ elif name == "__dealloc__":
3010
+ name = "<del>"
3011
+ return super(CppClassScope, self).lookup_here(name)
3012
+
3013
+ def is_cpp(self):
3014
+ # Whatever the global environment, always treat cppclass with C++ rules.
3015
+ # (Cython will emit warnings elsewhere)
3016
+ return True
3017
+
3018
+
3019
+ class CppScopedEnumScope(Scope):
3020
+ # Namespace of a ScopedEnum
3021
+
3022
+ def __init__(self, name, outer_scope):
3023
+ Scope.__init__(self, name, outer_scope, None)
3024
+
3025
+ def declare_var(self, name, type, pos,
3026
+ cname=None, visibility='extern', pytyping_modifiers=None):
3027
+ # Add an entry for an attribute.
3028
+ if not cname:
3029
+ cname = name
3030
+ self._reject_pytyping_modifiers(pos, pytyping_modifiers)
3031
+ entry = self.declare(name, cname, type, pos, visibility)
3032
+ entry.is_variable = True
3033
+ return entry
3034
+
3035
+
3036
+ class PropertyScope(Scope):
3037
+ # Scope holding the __get__, __set__ and __del__ methods for
3038
+ # a property of an extension type.
3039
+ #
3040
+ # parent_type PyExtensionType The type to which the property belongs
3041
+
3042
+ is_property_scope = 1
3043
+
3044
+ def __init__(self, name, class_scope):
3045
+ # outer scope is None for some internal properties
3046
+ outer_scope = class_scope.global_scope() if class_scope.outer_scope else None
3047
+ Scope.__init__(self, name, outer_scope, parent_scope=class_scope)
3048
+ self.parent_type = class_scope.parent_type
3049
+ self.directives = class_scope.directives
3050
+
3051
+ def declare_cfunction(self, name, type, pos, *args, **kwargs):
3052
+ """Declare a C property function.
3053
+ """
3054
+ if name=="__get__":
3055
+ if type.return_type.is_void:
3056
+ error(pos, "C property getter cannot return 'void'")
3057
+ if len(type.args) != 1:
3058
+ error(pos, "C property getter must have a single (self) argument")
3059
+
3060
+ if name=="__set__":
3061
+ # Allow only 'void noexcept' and 'int except(?) -1'.
3062
+ if type.return_type.is_void:
3063
+ if type.exception_check or type.exception_value is not None:
3064
+ error(pos, "C property setter needs 'noexcept' if declared 'void'")
3065
+ elif type.return_type in (PyrexTypes.c_int_type, PyrexTypes.c_returncode_type):
3066
+ if type.exception_value is not None and type.exception_value.python_value != -1:
3067
+ error(pos, f"C property setter with 'int' return needs explicit 'except -1' or 'except? -1'")
3068
+ else:
3069
+ error(pos, "C property setter must return void or an 'int' error code, -1 (error) or 0 (ok)")
3070
+ if len(type.args) != 2:
3071
+ error(pos, "C property setter must have two arguments (self and value)")
3072
+
3073
+ if type.args and not (type.args[0].type.is_pyobject or type.args[0].type is self.parent_scope.parent_type):
3074
+ error(pos, "self argument of C property method must be an object")
3075
+ if type.args and type.args[0].type is py_object_type:
3076
+ # Set 'self' argument type to extension type.
3077
+ type.args[0].type = self.parent_scope.parent_type
3078
+
3079
+ entry = Scope.declare_cfunction(self, name, type, pos, *args, **kwargs)
3080
+ entry.is_cproperty = True
3081
+ return entry
3082
+
3083
+ def declare_pyfunction(self, name, pos, allow_redefine=False):
3084
+ # Add an entry for a method.
3085
+ signature = get_property_accessor_signature(name)
3086
+ if signature:
3087
+ entry = self.declare(name, name, py_object_type, pos, 'private')
3088
+ entry.is_special = 1
3089
+ entry.signature = signature
3090
+ return entry
3091
+ else:
3092
+ error(pos, "Only __get__, __set__ and __del__ methods allowed "
3093
+ "in a property declaration")
3094
+ return None
3095
+
3096
+
3097
+ class CQualifierScope(Scope):
3098
+
3099
+ def __init__(self, base_type_scope, is_const=False, is_volatile=False, is_restrict=False):
3100
+ Scope.__init__(
3101
+ self,
3102
+ 'cv_' + base_type_scope.name,
3103
+ base_type_scope.outer_scope,
3104
+ base_type_scope.parent_scope)
3105
+ self.base_type_scope = base_type_scope
3106
+ self.is_const = is_const
3107
+ self.is_volatile = is_volatile
3108
+ self.is_restrict = is_restrict
3109
+
3110
+ def lookup_here(self, name):
3111
+ entry = self.base_type_scope.lookup_here(name)
3112
+ if entry is not None:
3113
+ entry = copy.copy(entry)
3114
+ entry.type = PyrexTypes.c_qualifier_type(
3115
+ entry.type, self.is_const, self.is_volatile, is_restrict=False)
3116
+ return entry
3117
+
3118
+
3119
+ class TemplateScope(Scope):
3120
+ def __init__(self, name, outer_scope):
3121
+ Scope.__init__(self, name, outer_scope, None)
3122
+ self.directives = outer_scope.directives