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