Symtab.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  1. #
  2. # Symbol Table
  3. #
  4. from __future__ import absolute_import
  5. import re
  6. import copy
  7. import operator
  8. try:
  9. import __builtin__ as builtins
  10. except ImportError: # Py3
  11. import builtins
  12. from .Errors import warning, error, InternalError
  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_special_method_signature, get_property_accessor_signature)
  20. from . import Future
  21. from . import Code
  22. iso_c99_keywords = set(
  23. ['auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
  24. 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
  25. 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof',
  26. 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void',
  27. 'volatile', 'while',
  28. '_Bool', '_Complex'', _Imaginary', 'inline', 'restrict'])
  29. def c_safe_identifier(cname):
  30. # There are some C limitations on struct entry names.
  31. if ((cname[:2] == '__' and not (cname.startswith(Naming.pyrex_prefix)
  32. or cname in ('__weakref__', '__dict__')))
  33. or cname in iso_c99_keywords):
  34. cname = Naming.pyrex_prefix + cname
  35. return cname
  36. class BufferAux(object):
  37. writable_needed = False
  38. def __init__(self, buflocal_nd_var, rcbuf_var):
  39. self.buflocal_nd_var = buflocal_nd_var
  40. self.rcbuf_var = rcbuf_var
  41. def __repr__(self):
  42. return "<BufferAux %r>" % self.__dict__
  43. class Entry(object):
  44. # A symbol table entry in a Scope or ModuleNamespace.
  45. #
  46. # name string Python name of entity
  47. # cname string C name of entity
  48. # type PyrexType Type of entity
  49. # doc string Doc string
  50. # annotation ExprNode PEP 484/526 annotation
  51. # init string Initial value
  52. # visibility 'private' or 'public' or 'extern'
  53. # is_builtin boolean Is an entry in the Python builtins dict
  54. # is_cglobal boolean Is a C global variable
  55. # is_pyglobal boolean Is a Python module-level variable
  56. # or class attribute during
  57. # class construction
  58. # is_member boolean Is an assigned class member
  59. # is_pyclass_attr boolean Is a name in a Python class namespace
  60. # is_variable boolean Is a variable
  61. # is_cfunction boolean Is a C function
  62. # is_cmethod boolean Is a C method of an extension type
  63. # is_builtin_cmethod boolean Is a C method of a builtin type (implies is_cmethod)
  64. # is_unbound_cmethod boolean Is an unbound C method of an extension type
  65. # is_final_cmethod boolean Is non-overridable C method
  66. # is_inline_cmethod boolean Is inlined C method
  67. # is_anonymous boolean Is a anonymous pyfunction entry
  68. # is_type boolean Is a type definition
  69. # is_cclass boolean Is an extension class
  70. # is_cpp_class boolean Is a C++ class
  71. # is_const boolean Is a constant
  72. # is_property boolean Is a property of an extension type:
  73. # doc_cname string or None C const holding the docstring
  74. # getter_cname string C func for getting property
  75. # setter_cname string C func for setting or deleting property
  76. # is_self_arg boolean Is the "self" arg of an exttype method
  77. # is_arg boolean Is the arg of a method
  78. # is_local boolean Is a local variable
  79. # in_closure boolean Is referenced in an inner scope
  80. # in_subscope boolean Belongs to a generator expression scope
  81. # is_readonly boolean Can't be assigned to
  82. # func_cname string C func implementing Python func
  83. # func_modifiers [string] C function modifiers ('inline')
  84. # pos position Source position where declared
  85. # namespace_cname string If is_pyglobal, the C variable
  86. # holding its home namespace
  87. # pymethdef_cname string PyMethodDef structure
  88. # signature Signature Arg & return types for Python func
  89. # as_variable Entry Alternative interpretation of extension
  90. # type name or builtin C function as a variable
  91. # xdecref_cleanup boolean Use Py_XDECREF for error cleanup
  92. # in_cinclude boolean Suppress C declaration code
  93. # enum_values [Entry] For enum types, list of values
  94. # qualified_name string "modname.funcname" or "modname.classname"
  95. # or "modname.classname.funcname"
  96. # is_declared_generic boolean Is declared as PyObject * even though its
  97. # type is an extension type
  98. # as_module None Module scope, if a cimported module
  99. # is_inherited boolean Is an inherited attribute of an extension type
  100. # pystring_cname string C name of Python version of string literal
  101. # is_interned boolean For string const entries, value is interned
  102. # is_identifier boolean For string const entries, value is an identifier
  103. # used boolean
  104. # is_special boolean Is a special method or property accessor
  105. # of an extension type
  106. # defined_in_pxd boolean Is defined in a .pxd file (not just declared)
  107. # api boolean Generate C API for C class or function
  108. # utility_code string Utility code needed when this entry is used
  109. #
  110. # buffer_aux BufferAux or None Extra information needed for buffer variables
  111. # inline_func_in_pxd boolean Hacky special case for inline function in pxd file.
  112. # Ideally this should not be necessary.
  113. # might_overflow boolean In an arithmetic expression that could cause
  114. # overflow (used for type inference).
  115. # utility_code_definition For some Cython builtins, the utility code
  116. # which contains the definition of the entry.
  117. # Currently only supported for CythonScope entries.
  118. # error_on_uninitialized Have Control Flow issue an error when this entry is
  119. # used uninitialized
  120. # cf_used boolean Entry is used
  121. # is_fused_specialized boolean Whether this entry of a cdef or def function
  122. # is a specialization
  123. # TODO: utility_code and utility_code_definition serves the same purpose...
  124. inline_func_in_pxd = False
  125. borrowed = 0
  126. init = ""
  127. annotation = None
  128. visibility = 'private'
  129. is_builtin = 0
  130. is_cglobal = 0
  131. is_pyglobal = 0
  132. is_member = 0
  133. is_pyclass_attr = 0
  134. is_variable = 0
  135. is_cfunction = 0
  136. is_cmethod = 0
  137. is_builtin_cmethod = False
  138. is_unbound_cmethod = 0
  139. is_final_cmethod = 0
  140. is_inline_cmethod = 0
  141. is_anonymous = 0
  142. is_type = 0
  143. is_cclass = 0
  144. is_cpp_class = 0
  145. is_const = 0
  146. is_property = 0
  147. doc_cname = None
  148. getter_cname = None
  149. setter_cname = None
  150. is_self_arg = 0
  151. is_arg = 0
  152. is_local = 0
  153. in_closure = 0
  154. from_closure = 0
  155. in_subscope = 0
  156. is_declared_generic = 0
  157. is_readonly = 0
  158. pyfunc_cname = None
  159. func_cname = None
  160. func_modifiers = []
  161. final_func_cname = None
  162. doc = None
  163. as_variable = None
  164. xdecref_cleanup = 0
  165. in_cinclude = 0
  166. as_module = None
  167. is_inherited = 0
  168. pystring_cname = None
  169. is_identifier = 0
  170. is_interned = 0
  171. used = 0
  172. is_special = 0
  173. defined_in_pxd = 0
  174. is_implemented = 0
  175. api = 0
  176. utility_code = None
  177. is_overridable = 0
  178. buffer_aux = None
  179. prev_entry = None
  180. might_overflow = 0
  181. fused_cfunction = None
  182. is_fused_specialized = False
  183. utility_code_definition = None
  184. needs_property = False
  185. in_with_gil_block = 0
  186. from_cython_utility_code = None
  187. error_on_uninitialized = False
  188. cf_used = True
  189. outer_entry = None
  190. def __init__(self, name, cname, type, pos = None, init = None):
  191. self.name = name
  192. self.cname = cname
  193. self.type = type
  194. self.pos = pos
  195. self.init = init
  196. self.overloaded_alternatives = []
  197. self.cf_assignments = []
  198. self.cf_references = []
  199. self.inner_entries = []
  200. self.defining_entry = self
  201. def __repr__(self):
  202. return "%s(<%x>, name=%s, type=%s)" % (type(self).__name__, id(self), self.name, self.type)
  203. def already_declared_here(self):
  204. error(self.pos, "Previous declaration is here")
  205. def redeclared(self, pos):
  206. error(pos, "'%s' does not match previous declaration" % self.name)
  207. self.already_declared_here()
  208. def all_alternatives(self):
  209. return [self] + self.overloaded_alternatives
  210. def all_entries(self):
  211. return [self] + self.inner_entries
  212. def __lt__(left, right):
  213. if isinstance(left, Entry) and isinstance(right, Entry):
  214. return (left.name, left.cname) < (right.name, right.cname)
  215. else:
  216. return NotImplemented
  217. class InnerEntry(Entry):
  218. """
  219. An entry in a closure scope that represents the real outer Entry.
  220. """
  221. from_closure = True
  222. def __init__(self, outer_entry, scope):
  223. Entry.__init__(self, outer_entry.name,
  224. outer_entry.cname,
  225. outer_entry.type,
  226. outer_entry.pos)
  227. self.outer_entry = outer_entry
  228. self.scope = scope
  229. # share state with (outermost) defining entry
  230. outermost_entry = outer_entry
  231. while outermost_entry.outer_entry:
  232. outermost_entry = outermost_entry.outer_entry
  233. self.defining_entry = outermost_entry
  234. self.inner_entries = outermost_entry.inner_entries
  235. self.cf_assignments = outermost_entry.cf_assignments
  236. self.cf_references = outermost_entry.cf_references
  237. self.overloaded_alternatives = outermost_entry.overloaded_alternatives
  238. self.inner_entries.append(self)
  239. def __getattr__(self, name):
  240. if name.startswith('__'):
  241. # we wouldn't have been called if it was there
  242. raise AttributeError(name)
  243. return getattr(self.defining_entry, name)
  244. def all_entries(self):
  245. return self.defining_entry.all_entries()
  246. class Scope(object):
  247. # name string Unqualified name
  248. # outer_scope Scope or None Enclosing scope
  249. # entries {string : Entry} Python name to entry, non-types
  250. # const_entries [Entry] Constant entries
  251. # type_entries [Entry] Struct/union/enum/typedef/exttype entries
  252. # sue_entries [Entry] Struct/union/enum entries
  253. # arg_entries [Entry] Function argument entries
  254. # var_entries [Entry] User-defined variable entries
  255. # pyfunc_entries [Entry] Python function entries
  256. # cfunc_entries [Entry] C function entries
  257. # c_class_entries [Entry] All extension type entries
  258. # cname_to_entry {string : Entry} Temp cname to entry mapping
  259. # return_type PyrexType or None Return type of function owning scope
  260. # is_builtin_scope boolean Is the builtin scope of Python/Cython
  261. # is_py_class_scope boolean Is a Python class scope
  262. # is_c_class_scope boolean Is an extension type scope
  263. # is_closure_scope boolean Is a closure scope
  264. # is_passthrough boolean Outer scope is passed directly
  265. # is_cpp_class_scope boolean Is a C++ class scope
  266. # is_property_scope boolean Is a extension type property scope
  267. # scope_prefix string Disambiguator for C names
  268. # in_cinclude boolean Suppress C declaration code
  269. # qualified_name string "modname" or "modname.classname"
  270. # Python strings in this scope
  271. # nogil boolean In a nogil section
  272. # directives dict Helper variable for the recursive
  273. # analysis, contains directive values.
  274. # is_internal boolean Is only used internally (simpler setup)
  275. is_builtin_scope = 0
  276. is_py_class_scope = 0
  277. is_c_class_scope = 0
  278. is_closure_scope = 0
  279. is_genexpr_scope = 0
  280. is_passthrough = 0
  281. is_cpp_class_scope = 0
  282. is_property_scope = 0
  283. is_module_scope = 0
  284. is_internal = 0
  285. scope_prefix = ""
  286. in_cinclude = 0
  287. nogil = 0
  288. fused_to_specific = None
  289. return_type = None
  290. def __init__(self, name, outer_scope, parent_scope):
  291. # The outer_scope is the next scope in the lookup chain.
  292. # The parent_scope is used to derive the qualified name of this scope.
  293. self.name = name
  294. self.outer_scope = outer_scope
  295. self.parent_scope = parent_scope
  296. mangled_name = "%d%s_" % (len(name), name.replace('.', '_dot_'))
  297. qual_scope = self.qualifying_scope()
  298. if qual_scope:
  299. self.qualified_name = qual_scope.qualify_name(name)
  300. self.scope_prefix = qual_scope.scope_prefix + mangled_name
  301. else:
  302. self.qualified_name = EncodedString(name)
  303. self.scope_prefix = mangled_name
  304. self.entries = {}
  305. self.subscopes = set()
  306. self.const_entries = []
  307. self.type_entries = []
  308. self.sue_entries = []
  309. self.arg_entries = []
  310. self.var_entries = []
  311. self.pyfunc_entries = []
  312. self.cfunc_entries = []
  313. self.c_class_entries = []
  314. self.defined_c_classes = []
  315. self.imported_c_classes = {}
  316. self.cname_to_entry = {}
  317. self.string_to_entry = {}
  318. self.identifier_to_entry = {}
  319. self.num_to_entry = {}
  320. self.obj_to_entry = {}
  321. self.buffer_entries = []
  322. self.lambda_defs = []
  323. self.id_counters = {}
  324. def __deepcopy__(self, memo):
  325. return self
  326. def merge_in(self, other, merge_unused=True, whitelist=None):
  327. # Use with care...
  328. entries = []
  329. for name, entry in other.entries.items():
  330. if not whitelist or name in whitelist:
  331. if entry.used or merge_unused:
  332. entries.append((name, entry))
  333. self.entries.update(entries)
  334. for attr in ('const_entries',
  335. 'type_entries',
  336. 'sue_entries',
  337. 'arg_entries',
  338. 'var_entries',
  339. 'pyfunc_entries',
  340. 'cfunc_entries',
  341. 'c_class_entries'):
  342. self_entries = getattr(self, attr)
  343. names = set(e.name for e in self_entries)
  344. for entry in getattr(other, attr):
  345. if (entry.used or merge_unused) and entry.name not in names:
  346. self_entries.append(entry)
  347. def __str__(self):
  348. return "<%s %s>" % (self.__class__.__name__, self.qualified_name)
  349. def qualifying_scope(self):
  350. return self.parent_scope
  351. def mangle(self, prefix, name = None):
  352. if name:
  353. return "%s%s%s" % (prefix, self.scope_prefix, name)
  354. else:
  355. return self.parent_scope.mangle(prefix, self.name)
  356. def mangle_internal(self, name):
  357. # Mangle an internal name so as not to clash with any
  358. # user-defined name in this scope.
  359. prefix = "%s%s_" % (Naming.pyrex_prefix, name)
  360. return self.mangle(prefix)
  361. #return self.parent_scope.mangle(prefix, self.name)
  362. def mangle_class_private_name(self, name):
  363. if self.parent_scope:
  364. return self.parent_scope.mangle_class_private_name(name)
  365. return name
  366. def next_id(self, name=None):
  367. # Return a cname fragment that is unique for this module
  368. counters = self.global_scope().id_counters
  369. try:
  370. count = counters[name] + 1
  371. except KeyError:
  372. count = 0
  373. counters[name] = count
  374. if name:
  375. if not count:
  376. # unique names don't need a suffix, reoccurrences will get one
  377. return name
  378. return '%s%d' % (name, count)
  379. else:
  380. return '%d' % count
  381. def global_scope(self):
  382. """ Return the module-level scope containing this scope. """
  383. return self.outer_scope.global_scope()
  384. def builtin_scope(self):
  385. """ Return the module-level scope containing this scope. """
  386. return self.outer_scope.builtin_scope()
  387. def iter_local_scopes(self):
  388. yield self
  389. if self.subscopes:
  390. for scope in sorted(self.subscopes, key=operator.attrgetter('scope_prefix')):
  391. yield scope
  392. def declare(self, name, cname, type, pos, visibility, shadow = 0, is_type = 0, create_wrapper = 0):
  393. # Create new entry, and add to dictionary if
  394. # name is not None. Reports a warning if already
  395. # declared.
  396. if type.is_buffer and not isinstance(self, LocalScope): # and not is_type:
  397. error(pos, 'Buffer types only allowed as function local variables')
  398. if not self.in_cinclude and cname and re.match("^_[_A-Z]+$", cname):
  399. # See http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html#Reserved-Names
  400. warning(pos, "'%s' is a reserved name in C." % cname, -1)
  401. entries = self.entries
  402. if name and name in entries and not shadow:
  403. old_entry = entries[name]
  404. # Reject redeclared C++ functions only if they have the same type signature.
  405. cpp_override_allowed = False
  406. if type.is_cfunction and old_entry.type.is_cfunction and self.is_cpp():
  407. for alt_entry in old_entry.all_alternatives():
  408. if type == alt_entry.type:
  409. if name == '<init>' and not type.args:
  410. # Cython pre-declares the no-args constructor - allow later user definitions.
  411. cpp_override_allowed = True
  412. break
  413. else:
  414. cpp_override_allowed = True
  415. if cpp_override_allowed:
  416. # C++ function/method overrides with different signatures are ok.
  417. pass
  418. elif self.is_cpp_class_scope and entries[name].is_inherited:
  419. # Likewise ignore inherited classes.
  420. pass
  421. elif visibility == 'extern':
  422. # Silenced outside of "cdef extern" blocks, until we have a safe way to
  423. # prevent pxd-defined cpdef functions from ending up here.
  424. warning(pos, "'%s' redeclared " % name, 1 if self.in_cinclude else 0)
  425. elif visibility != 'ignore':
  426. error(pos, "'%s' redeclared " % name)
  427. entries[name].already_declared_here()
  428. entry = Entry(name, cname, type, pos = pos)
  429. entry.in_cinclude = self.in_cinclude
  430. entry.create_wrapper = create_wrapper
  431. if name:
  432. entry.qualified_name = self.qualify_name(name)
  433. # if name in entries and self.is_cpp():
  434. # entries[name].overloaded_alternatives.append(entry)
  435. # else:
  436. # entries[name] = entry
  437. if not shadow:
  438. entries[name] = entry
  439. if type.is_memoryviewslice:
  440. from . import MemoryView
  441. entry.init = MemoryView.memslice_entry_init
  442. entry.scope = self
  443. entry.visibility = visibility
  444. return entry
  445. def qualify_name(self, name):
  446. return EncodedString("%s.%s" % (self.qualified_name, name))
  447. def declare_const(self, name, type, value, pos, cname = None, visibility = 'private', api = 0, create_wrapper = 0):
  448. # Add an entry for a named constant.
  449. if not cname:
  450. if self.in_cinclude or (visibility == 'public' or api):
  451. cname = name
  452. else:
  453. cname = self.mangle(Naming.enum_prefix, name)
  454. entry = self.declare(name, cname, type, pos, visibility, create_wrapper = create_wrapper)
  455. entry.is_const = 1
  456. entry.value_node = value
  457. return entry
  458. def declare_type(self, name, type, pos,
  459. cname = None, visibility = 'private', api = 0, defining = 1,
  460. shadow = 0, template = 0):
  461. # Add an entry for a type definition.
  462. if not cname:
  463. cname = name
  464. entry = self.declare(name, cname, type, pos, visibility, shadow,
  465. is_type=True)
  466. entry.is_type = 1
  467. entry.api = api
  468. if defining:
  469. self.type_entries.append(entry)
  470. if not template:
  471. type.entry = entry
  472. # here we would set as_variable to an object representing this type
  473. return entry
  474. def declare_typedef(self, name, base_type, pos, cname = None,
  475. visibility = 'private', api = 0):
  476. if not cname:
  477. if self.in_cinclude or (visibility != 'private' or api):
  478. cname = name
  479. else:
  480. cname = self.mangle(Naming.type_prefix, name)
  481. try:
  482. if self.is_cpp_class_scope:
  483. namespace = self.outer_scope.lookup(self.name).type
  484. else:
  485. namespace = None
  486. type = PyrexTypes.create_typedef_type(name, base_type, cname,
  487. (visibility == 'extern'),
  488. namespace)
  489. except ValueError as e:
  490. error(pos, e.args[0])
  491. type = PyrexTypes.error_type
  492. entry = self.declare_type(name, type, pos, cname,
  493. visibility = visibility, api = api)
  494. type.qualified_name = entry.qualified_name
  495. return entry
  496. def declare_struct_or_union(self, name, kind, scope,
  497. typedef_flag, pos, cname = None,
  498. visibility = 'private', api = 0,
  499. packed = False):
  500. # Add an entry for a struct or union definition.
  501. if not cname:
  502. if self.in_cinclude or (visibility == 'public' or api):
  503. cname = name
  504. else:
  505. cname = self.mangle(Naming.type_prefix, name)
  506. entry = self.lookup_here(name)
  507. if not entry:
  508. type = PyrexTypes.CStructOrUnionType(
  509. name, kind, scope, typedef_flag, cname, packed)
  510. entry = self.declare_type(name, type, pos, cname,
  511. visibility = visibility, api = api,
  512. defining = scope is not None)
  513. self.sue_entries.append(entry)
  514. type.entry = entry
  515. else:
  516. if not (entry.is_type and entry.type.is_struct_or_union
  517. and entry.type.kind == kind):
  518. warning(pos, "'%s' redeclared " % name, 0)
  519. elif scope and entry.type.scope:
  520. warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
  521. else:
  522. self.check_previous_typedef_flag(entry, typedef_flag, pos)
  523. self.check_previous_visibility(entry, visibility, pos)
  524. if scope:
  525. entry.type.scope = scope
  526. self.type_entries.append(entry)
  527. if self.is_cpp_class_scope:
  528. entry.type.namespace = self.outer_scope.lookup(self.name).type
  529. return entry
  530. def declare_cpp_class(self, name, scope,
  531. pos, cname = None, base_classes = (),
  532. visibility = 'extern', templates = None):
  533. if cname is None:
  534. if self.in_cinclude or (visibility != 'private'):
  535. cname = name
  536. else:
  537. cname = self.mangle(Naming.type_prefix, name)
  538. base_classes = list(base_classes)
  539. entry = self.lookup_here(name)
  540. if not entry:
  541. type = PyrexTypes.CppClassType(
  542. name, scope, cname, base_classes, templates = templates)
  543. entry = self.declare_type(name, type, pos, cname,
  544. visibility = visibility, defining = scope is not None)
  545. self.sue_entries.append(entry)
  546. else:
  547. if not (entry.is_type and entry.type.is_cpp_class):
  548. error(pos, "'%s' redeclared " % name)
  549. entry.already_declared_here()
  550. return None
  551. elif scope and entry.type.scope:
  552. warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
  553. else:
  554. if scope:
  555. entry.type.scope = scope
  556. self.type_entries.append(entry)
  557. if base_classes:
  558. if entry.type.base_classes and entry.type.base_classes != base_classes:
  559. error(pos, "Base type does not match previous declaration")
  560. entry.already_declared_here()
  561. else:
  562. entry.type.base_classes = base_classes
  563. if templates or entry.type.templates:
  564. if templates != entry.type.templates:
  565. error(pos, "Template parameters do not match previous declaration")
  566. entry.already_declared_here()
  567. def declare_inherited_attributes(entry, base_classes):
  568. for base_class in base_classes:
  569. if base_class is PyrexTypes.error_type:
  570. continue
  571. if base_class.scope is None:
  572. error(pos, "Cannot inherit from incomplete type")
  573. else:
  574. declare_inherited_attributes(entry, base_class.base_classes)
  575. entry.type.scope.declare_inherited_cpp_attributes(base_class)
  576. if scope:
  577. declare_inherited_attributes(entry, base_classes)
  578. scope.declare_var(name="this", cname="this", type=PyrexTypes.CPtrType(entry.type), pos=entry.pos)
  579. if self.is_cpp_class_scope:
  580. entry.type.namespace = self.outer_scope.lookup(self.name).type
  581. return entry
  582. def check_previous_typedef_flag(self, entry, typedef_flag, pos):
  583. if typedef_flag != entry.type.typedef_flag:
  584. error(pos, "'%s' previously declared using '%s'" % (
  585. entry.name, ("cdef", "ctypedef")[entry.type.typedef_flag]))
  586. def check_previous_visibility(self, entry, visibility, pos):
  587. if entry.visibility != visibility:
  588. error(pos, "'%s' previously declared as '%s'" % (
  589. entry.name, entry.visibility))
  590. def declare_enum(self, name, pos, cname, typedef_flag,
  591. visibility = 'private', api = 0, create_wrapper = 0):
  592. if name:
  593. if not cname:
  594. if (self.in_cinclude or visibility == 'public'
  595. or visibility == 'extern' or api):
  596. cname = name
  597. else:
  598. cname = self.mangle(Naming.type_prefix, name)
  599. if self.is_cpp_class_scope:
  600. namespace = self.outer_scope.lookup(self.name).type
  601. else:
  602. namespace = None
  603. type = PyrexTypes.CEnumType(name, cname, typedef_flag, namespace)
  604. else:
  605. type = PyrexTypes.c_anon_enum_type
  606. entry = self.declare_type(name, type, pos, cname = cname,
  607. visibility = visibility, api = api)
  608. entry.create_wrapper = create_wrapper
  609. entry.enum_values = []
  610. self.sue_entries.append(entry)
  611. return entry
  612. def declare_tuple_type(self, pos, components):
  613. return self.outer_scope.declare_tuple_type(pos, components)
  614. def declare_var(self, name, type, pos,
  615. cname = None, visibility = 'private',
  616. api = 0, in_pxd = 0, is_cdef = 0):
  617. # Add an entry for a variable.
  618. if not cname:
  619. if visibility != 'private' or api:
  620. cname = name
  621. else:
  622. cname = self.mangle(Naming.var_prefix, name)
  623. if type.is_cpp_class and visibility != 'extern':
  624. type.check_nullary_constructor(pos)
  625. entry = self.declare(name, cname, type, pos, visibility)
  626. entry.is_variable = 1
  627. if in_pxd and visibility != 'extern':
  628. entry.defined_in_pxd = 1
  629. entry.used = 1
  630. if api:
  631. entry.api = 1
  632. entry.used = 1
  633. return entry
  634. def declare_builtin(self, name, pos):
  635. return self.outer_scope.declare_builtin(name, pos)
  636. def _declare_pyfunction(self, name, pos, visibility='extern', entry=None):
  637. if entry and not entry.type.is_cfunction:
  638. error(pos, "'%s' already declared" % name)
  639. error(entry.pos, "Previous declaration is here")
  640. entry = self.declare_var(name, py_object_type, pos, visibility=visibility)
  641. entry.signature = pyfunction_signature
  642. self.pyfunc_entries.append(entry)
  643. return entry
  644. def declare_pyfunction(self, name, pos, allow_redefine=False, visibility='extern'):
  645. # Add an entry for a Python function.
  646. entry = self.lookup_here(name)
  647. if not allow_redefine:
  648. return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
  649. if entry:
  650. if entry.type.is_unspecified:
  651. entry.type = py_object_type
  652. elif entry.type is not py_object_type:
  653. return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
  654. else: # declare entry stub
  655. self.declare_var(name, py_object_type, pos, visibility=visibility)
  656. entry = self.declare_var(None, py_object_type, pos,
  657. cname=name, visibility='private')
  658. entry.name = EncodedString(name)
  659. entry.qualified_name = self.qualify_name(name)
  660. entry.signature = pyfunction_signature
  661. entry.is_anonymous = True
  662. return entry
  663. def declare_lambda_function(self, lambda_name, pos):
  664. # Add an entry for an anonymous Python function.
  665. func_cname = self.mangle(Naming.lambda_func_prefix + u'funcdef_', lambda_name)
  666. pymethdef_cname = self.mangle(Naming.lambda_func_prefix + u'methdef_', lambda_name)
  667. qualified_name = self.qualify_name(lambda_name)
  668. entry = self.declare(None, func_cname, py_object_type, pos, 'private')
  669. entry.name = lambda_name
  670. entry.qualified_name = qualified_name
  671. entry.pymethdef_cname = pymethdef_cname
  672. entry.func_cname = func_cname
  673. entry.signature = pyfunction_signature
  674. entry.is_anonymous = True
  675. return entry
  676. def add_lambda_def(self, def_node):
  677. self.lambda_defs.append(def_node)
  678. def register_pyfunction(self, entry):
  679. self.pyfunc_entries.append(entry)
  680. def declare_cfunction(self, name, type, pos,
  681. cname=None, visibility='private', api=0, in_pxd=0,
  682. defining=0, modifiers=(), utility_code=None, overridable=False):
  683. # Add an entry for a C function.
  684. if not cname:
  685. if visibility != 'private' or api:
  686. cname = name
  687. else:
  688. cname = self.mangle(Naming.func_prefix, name)
  689. entry = self.lookup_here(name)
  690. if entry:
  691. if not in_pxd and visibility != entry.visibility and visibility == 'extern':
  692. # Previously declared, but now extern => treat this
  693. # as implementing the function, using the new cname
  694. defining = True
  695. visibility = entry.visibility
  696. entry.cname = cname
  697. entry.func_cname = cname
  698. if visibility != 'private' and visibility != entry.visibility:
  699. warning(pos, "Function '%s' previously declared as '%s', now as '%s'" % (name, entry.visibility, visibility), 1)
  700. if overridable != entry.is_overridable:
  701. warning(pos, "Function '%s' previously declared as '%s'" % (
  702. name, 'cpdef' if overridable else 'cdef'), 1)
  703. if entry.type.same_as(type):
  704. # Fix with_gil vs nogil.
  705. entry.type = entry.type.with_with_gil(type.with_gil)
  706. else:
  707. if visibility == 'extern' and entry.visibility == 'extern':
  708. can_override = False
  709. if self.is_cpp():
  710. can_override = True
  711. elif cname:
  712. # if all alternatives have different cnames,
  713. # it's safe to allow signature overrides
  714. for alt_entry in entry.all_alternatives():
  715. if not alt_entry.cname or cname == alt_entry.cname:
  716. break # cname not unique!
  717. else:
  718. can_override = True
  719. if can_override:
  720. temp = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
  721. temp.overloaded_alternatives = entry.all_alternatives()
  722. entry = temp
  723. else:
  724. warning(pos, "Function signature does not match previous declaration", 1)
  725. entry.type = type
  726. elif not in_pxd and entry.defined_in_pxd and type.compatible_signature_with(entry.type):
  727. # TODO: check that this was done by a signature optimisation and not a user error.
  728. #warning(pos, "Function signature does not match previous declaration", 1)
  729. entry.type = type
  730. else:
  731. error(pos, "Function signature does not match previous declaration")
  732. else:
  733. entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
  734. entry.func_cname = cname
  735. entry.is_overridable = overridable
  736. if in_pxd and visibility != 'extern':
  737. entry.defined_in_pxd = 1
  738. if api:
  739. entry.api = 1
  740. if not defining and not in_pxd and visibility != 'extern':
  741. error(pos, "Non-extern C function '%s' declared but not defined" % name)
  742. if defining:
  743. entry.is_implemented = True
  744. if modifiers:
  745. entry.func_modifiers = modifiers
  746. if utility_code:
  747. assert not entry.utility_code, "duplicate utility code definition in entry %s (%s)" % (name, cname)
  748. entry.utility_code = utility_code
  749. if overridable:
  750. # names of cpdef functions can be used as variables and can be assigned to
  751. var_entry = Entry(name, cname, py_object_type) # FIXME: cname?
  752. var_entry.qualified_name = self.qualify_name(name)
  753. var_entry.is_variable = 1
  754. var_entry.is_pyglobal = 1
  755. var_entry.scope = entry.scope
  756. entry.as_variable = var_entry
  757. type.entry = entry
  758. return entry
  759. def add_cfunction(self, name, type, pos, cname, visibility, modifiers, inherited=False):
  760. # Add a C function entry without giving it a func_cname.
  761. entry = self.declare(name, cname, type, pos, visibility)
  762. entry.is_cfunction = 1
  763. if modifiers:
  764. entry.func_modifiers = modifiers
  765. if inherited or type.is_fused:
  766. self.cfunc_entries.append(entry)
  767. else:
  768. # For backwards compatibility reasons, we must keep all non-fused methods
  769. # before all fused methods, but separately for each type.
  770. i = len(self.cfunc_entries)
  771. for cfunc_entry in reversed(self.cfunc_entries):
  772. if cfunc_entry.is_inherited or not cfunc_entry.type.is_fused:
  773. break
  774. i -= 1
  775. self.cfunc_entries.insert(i, entry)
  776. return entry
  777. def find(self, name, pos):
  778. # Look up name, report error if not found.
  779. entry = self.lookup(name)
  780. if entry:
  781. return entry
  782. else:
  783. error(pos, "'%s' is not declared" % name)
  784. def find_imported_module(self, path, pos):
  785. # Look up qualified name, must be a module, report error if not found.
  786. # Path is a list of names.
  787. scope = self
  788. for name in path:
  789. entry = scope.find(name, pos)
  790. if not entry:
  791. return None
  792. if entry.as_module:
  793. scope = entry.as_module
  794. else:
  795. error(pos, "'%s' is not a cimported module" % '.'.join(path))
  796. return None
  797. return scope
  798. def lookup(self, name):
  799. # Look up name in this scope or an enclosing one.
  800. # Return None if not found.
  801. return (self.lookup_here(name)
  802. or (self.outer_scope and self.outer_scope.lookup(name))
  803. or None)
  804. def lookup_here(self, name):
  805. # Look up in this scope only, return None if not found.
  806. return self.entries.get(name, None)
  807. def lookup_target(self, name):
  808. # Look up name in this scope only. Declare as Python
  809. # variable if not found.
  810. entry = self.lookup_here(name)
  811. if not entry:
  812. entry = self.declare_var(name, py_object_type, None)
  813. return entry
  814. def lookup_type(self, name):
  815. entry = self.lookup(name)
  816. if entry and entry.is_type:
  817. if entry.type.is_fused and self.fused_to_specific:
  818. return entry.type.specialize(self.fused_to_specific)
  819. return entry.type
  820. def lookup_operator(self, operator, operands):
  821. if operands[0].type.is_cpp_class:
  822. obj_type = operands[0].type
  823. method = obj_type.scope.lookup("operator%s" % operator)
  824. if method is not None:
  825. arg_types = [arg.type for arg in operands[1:]]
  826. res = PyrexTypes.best_match([arg.type for arg in operands[1:]],
  827. method.all_alternatives())
  828. if res is not None:
  829. return res
  830. function = self.lookup("operator%s" % operator)
  831. function_alternatives = []
  832. if function is not None:
  833. function_alternatives = function.all_alternatives()
  834. # look-up nonmember methods listed within a class
  835. method_alternatives = []
  836. if len(operands)==2: # binary operators only
  837. for n in range(2):
  838. if operands[n].type.is_cpp_class:
  839. obj_type = operands[n].type
  840. method = obj_type.scope.lookup("operator%s" % operator)
  841. if method is not None:
  842. method_alternatives += method.all_alternatives()
  843. if (not method_alternatives) and (not function_alternatives):
  844. return None
  845. # select the unique alternatives
  846. all_alternatives = list(set(method_alternatives + function_alternatives))
  847. return PyrexTypes.best_match([arg.type for arg in operands],
  848. all_alternatives)
  849. def lookup_operator_for_types(self, pos, operator, types):
  850. from .Nodes import Node
  851. class FakeOperand(Node):
  852. pass
  853. operands = [FakeOperand(pos, type=type) for type in types]
  854. return self.lookup_operator(operator, operands)
  855. def use_utility_code(self, new_code):
  856. self.global_scope().use_utility_code(new_code)
  857. def use_entry_utility_code(self, entry):
  858. self.global_scope().use_entry_utility_code(entry)
  859. def defines_any(self, names):
  860. # Test whether any of the given names are defined in this scope.
  861. for name in names:
  862. if name in self.entries:
  863. return 1
  864. return 0
  865. def defines_any_special(self, names):
  866. # Test whether any of the given names are defined as special methods in this scope.
  867. for name in names:
  868. if name in self.entries and self.entries[name].is_special:
  869. return 1
  870. return 0
  871. def infer_types(self):
  872. from .TypeInference import get_type_inferer
  873. get_type_inferer().infer_types(self)
  874. def is_cpp(self):
  875. outer = self.outer_scope
  876. if outer is None:
  877. return False
  878. else:
  879. return outer.is_cpp()
  880. def add_include_file(self, filename, verbatim_include=None, late=False):
  881. self.outer_scope.add_include_file(filename, verbatim_include, late)
  882. class PreImportScope(Scope):
  883. namespace_cname = Naming.preimport_cname
  884. def __init__(self):
  885. Scope.__init__(self, Options.pre_import, None, None)
  886. def declare_builtin(self, name, pos):
  887. entry = self.declare(name, name, py_object_type, pos, 'private')
  888. entry.is_variable = True
  889. entry.is_pyglobal = True
  890. return entry
  891. class BuiltinScope(Scope):
  892. # The builtin namespace.
  893. is_builtin_scope = True
  894. def __init__(self):
  895. if Options.pre_import is None:
  896. Scope.__init__(self, "__builtin__", None, None)
  897. else:
  898. Scope.__init__(self, "__builtin__", PreImportScope(), None)
  899. self.type_names = {}
  900. for name, definition in sorted(self.builtin_entries.items()):
  901. cname, type = definition
  902. self.declare_var(name, type, None, cname)
  903. def lookup(self, name, language_level=None, str_is_str=None):
  904. # 'language_level' and 'str_is_str' are passed by ModuleScope
  905. if name == 'str':
  906. if str_is_str is None:
  907. str_is_str = language_level in (None, 2)
  908. if not str_is_str:
  909. name = 'unicode'
  910. return Scope.lookup(self, name)
  911. def declare_builtin(self, name, pos):
  912. if not hasattr(builtins, name):
  913. if self.outer_scope is not None:
  914. return self.outer_scope.declare_builtin(name, pos)
  915. else:
  916. if Options.error_on_unknown_names:
  917. error(pos, "undeclared name not builtin: %s" % name)
  918. else:
  919. warning(pos, "undeclared name not builtin: %s" % name, 2)
  920. def declare_builtin_cfunction(self, name, type, cname, python_equiv=None, utility_code=None):
  921. # If python_equiv == "*", the Python equivalent has the same name
  922. # as the entry, otherwise it has the name specified by python_equiv.
  923. name = EncodedString(name)
  924. entry = self.declare_cfunction(name, type, None, cname, visibility='extern',
  925. utility_code=utility_code)
  926. if python_equiv:
  927. if python_equiv == "*":
  928. python_equiv = name
  929. else:
  930. python_equiv = EncodedString(python_equiv)
  931. var_entry = Entry(python_equiv, python_equiv, py_object_type)
  932. var_entry.qualified_name = self.qualify_name(name)
  933. var_entry.is_variable = 1
  934. var_entry.is_builtin = 1
  935. var_entry.utility_code = utility_code
  936. var_entry.scope = entry.scope
  937. entry.as_variable = var_entry
  938. return entry
  939. def declare_builtin_type(self, name, cname, utility_code = None, objstruct_cname = None):
  940. name = EncodedString(name)
  941. type = PyrexTypes.BuiltinObjectType(name, cname, objstruct_cname)
  942. scope = CClassScope(name, outer_scope=None, visibility='extern')
  943. scope.directives = {}
  944. if name == 'bool':
  945. type.is_final_type = True
  946. type.set_scope(scope)
  947. self.type_names[name] = 1
  948. entry = self.declare_type(name, type, None, visibility='extern')
  949. entry.utility_code = utility_code
  950. var_entry = Entry(name = entry.name,
  951. type = self.lookup('type').type, # make sure "type" is the first type declared...
  952. pos = entry.pos,
  953. cname = entry.type.typeptr_cname)
  954. var_entry.qualified_name = self.qualify_name(name)
  955. var_entry.is_variable = 1
  956. var_entry.is_cglobal = 1
  957. var_entry.is_readonly = 1
  958. var_entry.is_builtin = 1
  959. var_entry.utility_code = utility_code
  960. var_entry.scope = self
  961. if Options.cache_builtins:
  962. var_entry.is_const = True
  963. entry.as_variable = var_entry
  964. return type
  965. def builtin_scope(self):
  966. return self
  967. builtin_entries = {
  968. "type": ["((PyObject*)&PyType_Type)", py_object_type],
  969. "bool": ["((PyObject*)&PyBool_Type)", py_object_type],
  970. "int": ["((PyObject*)&PyInt_Type)", py_object_type],
  971. "long": ["((PyObject*)&PyLong_Type)", py_object_type],
  972. "float": ["((PyObject*)&PyFloat_Type)", py_object_type],
  973. "complex":["((PyObject*)&PyComplex_Type)", py_object_type],
  974. "bytes": ["((PyObject*)&PyBytes_Type)", py_object_type],
  975. "bytearray": ["((PyObject*)&PyByteArray_Type)", py_object_type],
  976. "str": ["((PyObject*)&PyString_Type)", py_object_type],
  977. "unicode":["((PyObject*)&PyUnicode_Type)", py_object_type],
  978. "tuple": ["((PyObject*)&PyTuple_Type)", py_object_type],
  979. "list": ["((PyObject*)&PyList_Type)", py_object_type],
  980. "dict": ["((PyObject*)&PyDict_Type)", py_object_type],
  981. "set": ["((PyObject*)&PySet_Type)", py_object_type],
  982. "frozenset": ["((PyObject*)&PyFrozenSet_Type)", py_object_type],
  983. "slice": ["((PyObject*)&PySlice_Type)", py_object_type],
  984. # "file": ["((PyObject*)&PyFile_Type)", py_object_type], # not in Py3
  985. "None": ["Py_None", py_object_type],
  986. "False": ["Py_False", py_object_type],
  987. "True": ["Py_True", py_object_type],
  988. }
  989. const_counter = 1 # As a temporary solution for compiling code in pxds
  990. class ModuleScope(Scope):
  991. # module_name string Python name of the module
  992. # module_cname string C name of Python module object
  993. # #module_dict_cname string C name of module dict object
  994. # method_table_cname string C name of method table
  995. # doc string Module doc string
  996. # doc_cname string C name of module doc string
  997. # utility_code_list [UtilityCode] Queuing utility codes for forwarding to Code.py
  998. # c_includes {key: IncludeCode} C headers or verbatim code to be generated
  999. # See process_include() for more documentation
  1000. # string_to_entry {string : Entry} Map string const to entry
  1001. # identifier_to_entry {string : Entry} Map identifier string const to entry
  1002. # context Context
  1003. # parent_module Scope Parent in the import namespace
  1004. # module_entries {string : Entry} For cimport statements
  1005. # type_names {string : 1} Set of type names (used during parsing)
  1006. # included_files [string] Cython sources included with 'include'
  1007. # pxd_file_loaded boolean Corresponding .pxd file has been processed
  1008. # cimported_modules [ModuleScope] Modules imported with cimport
  1009. # types_imported {PyrexType} Set of types for which import code generated
  1010. # has_import_star boolean Module contains import *
  1011. # cpp boolean Compiling a C++ file
  1012. # is_cython_builtin boolean Is this the Cython builtin scope (or a child scope)
  1013. # is_package boolean Is this a package module? (__init__)
  1014. is_module_scope = 1
  1015. has_import_star = 0
  1016. is_cython_builtin = 0
  1017. old_style_globals = 0
  1018. def __init__(self, name, parent_module, context):
  1019. from . import Builtin
  1020. self.parent_module = parent_module
  1021. outer_scope = Builtin.builtin_scope
  1022. Scope.__init__(self, name, outer_scope, parent_module)
  1023. if name == "__init__":
  1024. # Treat Spam/__init__.pyx specially, so that when Python loads
  1025. # Spam/__init__.so, initSpam() is defined.
  1026. self.module_name = parent_module.module_name
  1027. self.is_package = True
  1028. else:
  1029. self.module_name = name
  1030. self.is_package = False
  1031. self.module_name = EncodedString(self.module_name)
  1032. self.context = context
  1033. self.module_cname = Naming.module_cname
  1034. self.module_dict_cname = Naming.moddict_cname
  1035. self.method_table_cname = Naming.methtable_cname
  1036. self.doc = ""
  1037. self.doc_cname = Naming.moddoc_cname
  1038. self.utility_code_list = []
  1039. self.module_entries = {}
  1040. self.c_includes = {}
  1041. self.type_names = dict(outer_scope.type_names)
  1042. self.pxd_file_loaded = 0
  1043. self.cimported_modules = []
  1044. self.types_imported = set()
  1045. self.included_files = []
  1046. self.has_extern_class = 0
  1047. self.cached_builtins = []
  1048. self.undeclared_cached_builtins = []
  1049. self.namespace_cname = self.module_cname
  1050. self._cached_tuple_types = {}
  1051. for var_name in ['__builtins__', '__name__', '__file__', '__doc__', '__path__',
  1052. '__spec__', '__loader__', '__package__', '__cached__']:
  1053. self.declare_var(EncodedString(var_name), py_object_type, None)
  1054. self.process_include(Code.IncludeCode("Python.h", initial=True))
  1055. def qualifying_scope(self):
  1056. return self.parent_module
  1057. def global_scope(self):
  1058. return self
  1059. def lookup(self, name, language_level=None, str_is_str=None):
  1060. entry = self.lookup_here(name)
  1061. if entry is not None:
  1062. return entry
  1063. if language_level is None:
  1064. language_level = self.context.language_level if self.context is not None else 3
  1065. if str_is_str is None:
  1066. str_is_str = language_level == 2 or (
  1067. self.context is not None and Future.unicode_literals not in self.context.future_directives)
  1068. return self.outer_scope.lookup(name, language_level=language_level, str_is_str=str_is_str)
  1069. def declare_tuple_type(self, pos, components):
  1070. components = tuple(components)
  1071. try:
  1072. ttype = self._cached_tuple_types[components]
  1073. except KeyError:
  1074. ttype = self._cached_tuple_types[components] = PyrexTypes.c_tuple_type(components)
  1075. cname = ttype.cname
  1076. entry = self.lookup_here(cname)
  1077. if not entry:
  1078. scope = StructOrUnionScope(cname)
  1079. for ix, component in enumerate(components):
  1080. scope.declare_var(name="f%s" % ix, type=component, pos=pos)
  1081. struct_entry = self.declare_struct_or_union(
  1082. cname + '_struct', 'struct', scope, typedef_flag=True, pos=pos, cname=cname)
  1083. self.type_entries.remove(struct_entry)
  1084. ttype.struct_entry = struct_entry
  1085. entry = self.declare_type(cname, ttype, pos, cname)
  1086. ttype.entry = entry
  1087. return entry
  1088. def declare_builtin(self, name, pos):
  1089. if not hasattr(builtins, name) \
  1090. and name not in Code.non_portable_builtins_map \
  1091. and name not in Code.uncachable_builtins:
  1092. if self.has_import_star:
  1093. entry = self.declare_var(name, py_object_type, pos)
  1094. return entry
  1095. else:
  1096. if Options.error_on_unknown_names:
  1097. error(pos, "undeclared name not builtin: %s" % name)
  1098. else:
  1099. warning(pos, "undeclared name not builtin: %s" % name, 2)
  1100. # unknown - assume it's builtin and look it up at runtime
  1101. entry = self.declare(name, None, py_object_type, pos, 'private')
  1102. entry.is_builtin = 1
  1103. return entry
  1104. if Options.cache_builtins:
  1105. for entry in self.cached_builtins:
  1106. if entry.name == name:
  1107. return entry
  1108. if name == 'globals' and not self.old_style_globals:
  1109. return self.outer_scope.lookup('__Pyx_Globals')
  1110. else:
  1111. entry = self.declare(None, None, py_object_type, pos, 'private')
  1112. if Options.cache_builtins and name not in Code.uncachable_builtins:
  1113. entry.is_builtin = 1
  1114. entry.is_const = 1 # cached
  1115. entry.name = name
  1116. entry.cname = Naming.builtin_prefix + name
  1117. self.cached_builtins.append(entry)
  1118. self.undeclared_cached_builtins.append(entry)
  1119. else:
  1120. entry.is_builtin = 1
  1121. entry.name = name
  1122. entry.qualified_name = self.builtin_scope().qualify_name(name)
  1123. return entry
  1124. def find_module(self, module_name, pos, relative_level=-1):
  1125. # Find a module in the import namespace, interpreting
  1126. # relative imports relative to this module's parent.
  1127. # Finds and parses the module's .pxd file if the module
  1128. # has not been referenced before.
  1129. relative_to = None
  1130. absolute_fallback = False
  1131. if relative_level is not None and relative_level > 0:
  1132. # explicit relative cimport
  1133. # error of going beyond top-level is handled in cimport node
  1134. relative_to = self
  1135. while relative_level > 0 and relative_to:
  1136. relative_to = relative_to.parent_module
  1137. relative_level -= 1
  1138. elif relative_level != 0:
  1139. # -1 or None: try relative cimport first, then absolute
  1140. relative_to = self.parent_module
  1141. absolute_fallback = True
  1142. module_scope = self.global_scope()
  1143. return module_scope.context.find_module(
  1144. module_name, relative_to=relative_to, pos=pos, absolute_fallback=absolute_fallback)
  1145. def find_submodule(self, name):
  1146. # Find and return scope for a submodule of this module,
  1147. # creating a new empty one if necessary. Doesn't parse .pxd.
  1148. if '.' in name:
  1149. name, submodule = name.split('.', 1)
  1150. else:
  1151. submodule = None
  1152. scope = self.lookup_submodule(name)
  1153. if not scope:
  1154. scope = ModuleScope(name, parent_module=self, context=self.context)
  1155. self.module_entries[name] = scope
  1156. if submodule:
  1157. scope = scope.find_submodule(submodule)
  1158. return scope
  1159. def lookup_submodule(self, name):
  1160. # Return scope for submodule of this module, or None.
  1161. if '.' in name:
  1162. name, submodule = name.split('.', 1)
  1163. else:
  1164. submodule = None
  1165. module = self.module_entries.get(name, None)
  1166. if submodule and module is not None:
  1167. module = module.lookup_submodule(submodule)
  1168. return module
  1169. def add_include_file(self, filename, verbatim_include=None, late=False):
  1170. """
  1171. Add `filename` as include file. Add `verbatim_include` as
  1172. verbatim text in the C file.
  1173. Both `filename` and `verbatim_include` can be `None` or empty.
  1174. """
  1175. inc = Code.IncludeCode(filename, verbatim_include, late=late)
  1176. self.process_include(inc)
  1177. def process_include(self, inc):
  1178. """
  1179. Add `inc`, which is an instance of `IncludeCode`, to this
  1180. `ModuleScope`. This either adds a new element to the
  1181. `c_includes` dict or it updates an existing entry.
  1182. In detail: the values of the dict `self.c_includes` are
  1183. instances of `IncludeCode` containing the code to be put in the
  1184. generated C file. The keys of the dict are needed to ensure
  1185. uniqueness in two ways: if an include file is specified in
  1186. multiple "cdef extern" blocks, only one `#include` statement is
  1187. generated. Second, the same include might occur multiple times
  1188. if we find it through multiple "cimport" paths. So we use the
  1189. generated code (of the form `#include "header.h"`) as dict key.
  1190. If verbatim code does not belong to any include file (i.e. it
  1191. was put in a `cdef extern from *` block), then we use a unique
  1192. dict key: namely, the `sortkey()`.
  1193. One `IncludeCode` object can contain multiple pieces of C code:
  1194. one optional "main piece" for the include file and several other
  1195. pieces for the verbatim code. The `IncludeCode.dict_update`
  1196. method merges the pieces of two different `IncludeCode` objects
  1197. if needed.
  1198. """
  1199. key = inc.mainpiece()
  1200. if key is None:
  1201. key = inc.sortkey()
  1202. inc.dict_update(self.c_includes, key)
  1203. inc = self.c_includes[key]
  1204. def add_imported_module(self, scope):
  1205. if scope not in self.cimported_modules:
  1206. for inc in scope.c_includes.values():
  1207. self.process_include(inc)
  1208. self.cimported_modules.append(scope)
  1209. for m in scope.cimported_modules:
  1210. self.add_imported_module(m)
  1211. def add_imported_entry(self, name, entry, pos):
  1212. if entry.is_pyglobal:
  1213. # Allow cimports to follow imports.
  1214. entry.is_variable = True
  1215. if entry not in self.entries:
  1216. self.entries[name] = entry
  1217. else:
  1218. warning(pos, "'%s' redeclared " % name, 0)
  1219. def declare_module(self, name, scope, pos):
  1220. # Declare a cimported module. This is represented as a
  1221. # Python module-level variable entry with a module
  1222. # scope attached to it. Reports an error and returns
  1223. # None if previously declared as something else.
  1224. entry = self.lookup_here(name)
  1225. if entry:
  1226. if entry.is_pyglobal and entry.as_module is scope:
  1227. return entry # Already declared as the same module
  1228. if not (entry.is_pyglobal and not entry.as_module):
  1229. # SAGE -- I put this here so Pyrex
  1230. # cimport's work across directories.
  1231. # Currently it tries to multiply define
  1232. # every module appearing in an import list.
  1233. # It shouldn't be an error for a module
  1234. # name to appear again, and indeed the generated
  1235. # code compiles fine.
  1236. return entry
  1237. else:
  1238. entry = self.declare_var(name, py_object_type, pos)
  1239. entry.is_variable = 0
  1240. entry.as_module = scope
  1241. self.add_imported_module(scope)
  1242. return entry
  1243. def declare_var(self, name, type, pos,
  1244. cname = None, visibility = 'private',
  1245. api = 0, in_pxd = 0, is_cdef = 0):
  1246. # Add an entry for a global variable. If it is a Python
  1247. # object type, and not declared with cdef, it will live
  1248. # in the module dictionary, otherwise it will be a C
  1249. # global variable.
  1250. if not visibility in ('private', 'public', 'extern'):
  1251. error(pos, "Module-level variable cannot be declared %s" % visibility)
  1252. if not is_cdef:
  1253. if type is unspecified_type:
  1254. type = py_object_type
  1255. if not (type.is_pyobject and not type.is_extension_type):
  1256. raise InternalError(
  1257. "Non-cdef global variable is not a generic Python object")
  1258. if not cname:
  1259. defining = not in_pxd
  1260. if visibility == 'extern' or (visibility == 'public' and defining):
  1261. cname = name
  1262. else:
  1263. cname = self.mangle(Naming.var_prefix, name)
  1264. entry = self.lookup_here(name)
  1265. if entry and entry.defined_in_pxd:
  1266. #if visibility != 'private' and visibility != entry.visibility:
  1267. # warning(pos, "Variable '%s' previously declared as '%s'" % (name, entry.visibility), 1)
  1268. if not entry.type.same_as(type):
  1269. if visibility == 'extern' and entry.visibility == 'extern':
  1270. warning(pos, "Variable '%s' type does not match previous declaration" % name, 1)
  1271. entry.type = type
  1272. #else:
  1273. # error(pos, "Variable '%s' type does not match previous declaration" % name)
  1274. if entry.visibility != "private":
  1275. mangled_cname = self.mangle(Naming.var_prefix, name)
  1276. if entry.cname == mangled_cname:
  1277. cname = name
  1278. entry.cname = name
  1279. if not entry.is_implemented:
  1280. entry.is_implemented = True
  1281. return entry
  1282. entry = Scope.declare_var(self, name, type, pos,
  1283. cname=cname, visibility=visibility,
  1284. api=api, in_pxd=in_pxd, is_cdef=is_cdef)
  1285. if is_cdef:
  1286. entry.is_cglobal = 1
  1287. if entry.type.declaration_value:
  1288. entry.init = entry.type.declaration_value
  1289. self.var_entries.append(entry)
  1290. else:
  1291. entry.is_pyglobal = 1
  1292. if Options.cimport_from_pyx:
  1293. entry.used = 1
  1294. return entry
  1295. def declare_cfunction(self, name, type, pos,
  1296. cname=None, visibility='private', api=0, in_pxd=0,
  1297. defining=0, modifiers=(), utility_code=None, overridable=False):
  1298. if not defining and 'inline' in modifiers:
  1299. # TODO(github/1736): Make this an error.
  1300. warning(pos, "Declarations should not be declared inline.", 1)
  1301. # Add an entry for a C function.
  1302. if not cname:
  1303. if visibility == 'extern' or (visibility == 'public' and defining):
  1304. cname = name
  1305. else:
  1306. cname = self.mangle(Naming.func_prefix, name)
  1307. if visibility == 'extern' and type.optional_arg_count:
  1308. error(pos, "Extern functions cannot have default arguments values.")
  1309. entry = self.lookup_here(name)
  1310. if entry and entry.defined_in_pxd:
  1311. if entry.visibility != "private":
  1312. mangled_cname = self.mangle(Naming.var_prefix, name)
  1313. if entry.cname == mangled_cname:
  1314. cname = name
  1315. entry.cname = cname
  1316. entry.func_cname = cname
  1317. entry = Scope.declare_cfunction(
  1318. self, name, type, pos,
  1319. cname=cname, visibility=visibility, api=api, in_pxd=in_pxd,
  1320. defining=defining, modifiers=modifiers, utility_code=utility_code,
  1321. overridable=overridable)
  1322. return entry
  1323. def declare_global(self, name, pos):
  1324. entry = self.lookup_here(name)
  1325. if not entry:
  1326. self.declare_var(name, py_object_type, pos)
  1327. def use_utility_code(self, new_code):
  1328. if new_code is not None:
  1329. self.utility_code_list.append(new_code)
  1330. def use_entry_utility_code(self, entry):
  1331. if entry is None:
  1332. return
  1333. if entry.utility_code:
  1334. self.utility_code_list.append(entry.utility_code)
  1335. if entry.utility_code_definition:
  1336. self.utility_code_list.append(entry.utility_code_definition)
  1337. def declare_c_class(self, name, pos, defining=0, implementing=0,
  1338. module_name=None, base_type=None, objstruct_cname=None,
  1339. typeobj_cname=None, typeptr_cname=None, visibility='private',
  1340. typedef_flag=0, api=0, check_size=None,
  1341. buffer_defaults=None, shadow=0):
  1342. # If this is a non-extern typedef class, expose the typedef, but use
  1343. # the non-typedef struct internally to avoid needing forward
  1344. # declarations for anonymous structs.
  1345. if typedef_flag and visibility != 'extern':
  1346. if not (visibility == 'public' or api):
  1347. warning(pos, "ctypedef only valid for 'extern' , 'public', and 'api'", 2)
  1348. objtypedef_cname = objstruct_cname
  1349. typedef_flag = 0
  1350. else:
  1351. objtypedef_cname = None
  1352. #
  1353. # Look for previous declaration as a type
  1354. #
  1355. entry = self.lookup_here(name)
  1356. if entry and not shadow:
  1357. type = entry.type
  1358. if not (entry.is_type and type.is_extension_type):
  1359. entry = None # Will cause redeclaration and produce an error
  1360. else:
  1361. scope = type.scope
  1362. if typedef_flag and (not scope or scope.defined):
  1363. self.check_previous_typedef_flag(entry, typedef_flag, pos)
  1364. if (scope and scope.defined) or (base_type and type.base_type):
  1365. if base_type and base_type is not type.base_type:
  1366. error(pos, "Base type does not match previous declaration")
  1367. if base_type and not type.base_type:
  1368. type.base_type = base_type
  1369. #
  1370. # Make a new entry if needed
  1371. #
  1372. if not entry or shadow:
  1373. type = PyrexTypes.PyExtensionType(
  1374. name, typedef_flag, base_type, visibility == 'extern', check_size=check_size)
  1375. type.pos = pos
  1376. type.buffer_defaults = buffer_defaults
  1377. if objtypedef_cname is not None:
  1378. type.objtypedef_cname = objtypedef_cname
  1379. if visibility == 'extern':
  1380. type.module_name = module_name
  1381. else:
  1382. type.module_name = self.qualified_name
  1383. if typeptr_cname:
  1384. type.typeptr_cname = typeptr_cname
  1385. else:
  1386. type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
  1387. entry = self.declare_type(name, type, pos, visibility = visibility,
  1388. defining = 0, shadow = shadow)
  1389. entry.is_cclass = True
  1390. if objstruct_cname:
  1391. type.objstruct_cname = objstruct_cname
  1392. elif not entry.in_cinclude:
  1393. type.objstruct_cname = self.mangle(Naming.objstruct_prefix, name)
  1394. else:
  1395. error(entry.pos,
  1396. "Object name required for 'public' or 'extern' C class")
  1397. self.attach_var_entry_to_c_class(entry)
  1398. self.c_class_entries.append(entry)
  1399. #
  1400. # Check for re-definition and create scope if needed
  1401. #
  1402. if not type.scope:
  1403. if defining or implementing:
  1404. scope = CClassScope(name = name, outer_scope = self,
  1405. visibility = visibility)
  1406. scope.directives = self.directives.copy()
  1407. if base_type and base_type.scope:
  1408. scope.declare_inherited_c_attributes(base_type.scope)
  1409. type.set_scope(scope)
  1410. self.type_entries.append(entry)
  1411. else:
  1412. if defining and type.scope.defined:
  1413. error(pos, "C class '%s' already defined" % name)
  1414. elif implementing and type.scope.implemented:
  1415. error(pos, "C class '%s' already implemented" % name)
  1416. #
  1417. # Fill in options, checking for compatibility with any previous declaration
  1418. #
  1419. if defining:
  1420. entry.defined_in_pxd = 1
  1421. if implementing: # So that filenames in runtime exceptions refer to
  1422. entry.pos = pos # the .pyx file and not the .pxd file
  1423. if visibility != 'private' and entry.visibility != visibility:
  1424. error(pos, "Class '%s' previously declared as '%s'"
  1425. % (name, entry.visibility))
  1426. if api:
  1427. entry.api = 1
  1428. if objstruct_cname:
  1429. if type.objstruct_cname and type.objstruct_cname != objstruct_cname:
  1430. error(pos, "Object struct name differs from previous declaration")
  1431. type.objstruct_cname = objstruct_cname
  1432. if typeobj_cname:
  1433. if type.typeobj_cname and type.typeobj_cname != typeobj_cname:
  1434. error(pos, "Type object name differs from previous declaration")
  1435. type.typeobj_cname = typeobj_cname
  1436. if self.directives.get('final'):
  1437. entry.type.is_final_type = True
  1438. # cdef classes are always exported, but we need to set it to
  1439. # distinguish between unused Cython utility code extension classes
  1440. entry.used = True
  1441. #
  1442. # Return new or existing entry
  1443. #
  1444. return entry
  1445. def allocate_vtable_names(self, entry):
  1446. # If extension type has a vtable, allocate vtable struct and
  1447. # slot names for it.
  1448. type = entry.type
  1449. if type.base_type and type.base_type.vtabslot_cname:
  1450. #print "...allocating vtabslot_cname because base type has one" ###
  1451. type.vtabslot_cname = "%s.%s" % (
  1452. Naming.obj_base_cname, type.base_type.vtabslot_cname)
  1453. elif type.scope and type.scope.cfunc_entries:
  1454. # one special case here: when inheriting from builtin
  1455. # types, the methods may also be built-in, in which
  1456. # case they won't need a vtable
  1457. entry_count = len(type.scope.cfunc_entries)
  1458. base_type = type.base_type
  1459. while base_type:
  1460. # FIXME: this will break if we ever get non-inherited C methods
  1461. if not base_type.scope or entry_count > len(base_type.scope.cfunc_entries):
  1462. break
  1463. if base_type.is_builtin_type:
  1464. # builtin base type defines all methods => no vtable needed
  1465. return
  1466. base_type = base_type.base_type
  1467. #print "...allocating vtabslot_cname because there are C methods" ###
  1468. type.vtabslot_cname = Naming.vtabslot_cname
  1469. if type.vtabslot_cname:
  1470. #print "...allocating other vtable related cnames" ###
  1471. type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name)
  1472. type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name)
  1473. def check_c_classes_pxd(self):
  1474. # Performs post-analysis checking and finishing up of extension types
  1475. # being implemented in this module. This is called only for the .pxd.
  1476. #
  1477. # Checks all extension types declared in this scope to
  1478. # make sure that:
  1479. #
  1480. # * The extension type is fully declared
  1481. #
  1482. # Also allocates a name for the vtable if needed.
  1483. #
  1484. for entry in self.c_class_entries:
  1485. # Check defined
  1486. if not entry.type.scope:
  1487. error(entry.pos, "C class '%s' is declared but not defined" % entry.name)
  1488. def check_c_class(self, entry):
  1489. type = entry.type
  1490. name = entry.name
  1491. visibility = entry.visibility
  1492. # Check defined
  1493. if not type.scope:
  1494. error(entry.pos, "C class '%s' is declared but not defined" % name)
  1495. # Generate typeobj_cname
  1496. if visibility != 'extern' and not type.typeobj_cname:
  1497. type.typeobj_cname = self.mangle(Naming.typeobj_prefix, name)
  1498. ## Generate typeptr_cname
  1499. #type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
  1500. # Check C methods defined
  1501. if type.scope:
  1502. for method_entry in type.scope.cfunc_entries:
  1503. if not method_entry.is_inherited and not method_entry.func_cname:
  1504. error(method_entry.pos, "C method '%s' is declared but not defined" %
  1505. method_entry.name)
  1506. # Allocate vtable name if necessary
  1507. if type.vtabslot_cname:
  1508. #print "ModuleScope.check_c_classes: allocating vtable cname for", self ###
  1509. type.vtable_cname = self.mangle(Naming.vtable_prefix, entry.name)
  1510. def check_c_classes(self):
  1511. # Performs post-analysis checking and finishing up of extension types
  1512. # being implemented in this module. This is called only for the main
  1513. # .pyx file scope, not for cimported .pxd scopes.
  1514. #
  1515. # Checks all extension types declared in this scope to
  1516. # make sure that:
  1517. #
  1518. # * The extension type is implemented
  1519. # * All required object and type names have been specified or generated
  1520. # * All non-inherited C methods are implemented
  1521. #
  1522. # Also allocates a name for the vtable if needed.
  1523. #
  1524. debug_check_c_classes = 0
  1525. if debug_check_c_classes:
  1526. print("Scope.check_c_classes: checking scope " + self.qualified_name)
  1527. for entry in self.c_class_entries:
  1528. if debug_check_c_classes:
  1529. print("...entry %s %s" % (entry.name, entry))
  1530. print("......type = ", entry.type)
  1531. print("......visibility = ", entry.visibility)
  1532. self.check_c_class(entry)
  1533. def check_c_functions(self):
  1534. # Performs post-analysis checking making sure all
  1535. # defined c functions are actually implemented.
  1536. for name, entry in self.entries.items():
  1537. if entry.is_cfunction:
  1538. if (entry.defined_in_pxd
  1539. and entry.scope is self
  1540. and entry.visibility != 'extern'
  1541. and not entry.in_cinclude
  1542. and not entry.is_implemented):
  1543. error(entry.pos, "Non-extern C function '%s' declared but not defined" % name)
  1544. def attach_var_entry_to_c_class(self, entry):
  1545. # The name of an extension class has to serve as both a type
  1546. # name and a variable name holding the type object. It is
  1547. # represented in the symbol table by a type entry with a
  1548. # variable entry attached to it. For the variable entry,
  1549. # we use a read-only C global variable whose name is an
  1550. # expression that refers to the type object.
  1551. from . import Builtin
  1552. var_entry = Entry(name = entry.name,
  1553. type = Builtin.type_type,
  1554. pos = entry.pos,
  1555. cname = entry.type.typeptr_cname)
  1556. var_entry.qualified_name = entry.qualified_name
  1557. var_entry.is_variable = 1
  1558. var_entry.is_cglobal = 1
  1559. var_entry.is_readonly = 1
  1560. var_entry.scope = entry.scope
  1561. entry.as_variable = var_entry
  1562. def is_cpp(self):
  1563. return self.cpp
  1564. def infer_types(self):
  1565. from .TypeInference import PyObjectTypeInferer
  1566. PyObjectTypeInferer().infer_types(self)
  1567. class LocalScope(Scope):
  1568. # Does the function have a 'with gil:' block?
  1569. has_with_gil_block = False
  1570. # Transient attribute, used for symbol table variable declarations
  1571. _in_with_gil_block = False
  1572. def __init__(self, name, outer_scope, parent_scope = None):
  1573. if parent_scope is None:
  1574. parent_scope = outer_scope
  1575. Scope.__init__(self, name, outer_scope, parent_scope)
  1576. def mangle(self, prefix, name):
  1577. return prefix + name
  1578. def declare_arg(self, name, type, pos):
  1579. # Add an entry for an argument of a function.
  1580. cname = self.mangle(Naming.var_prefix, name)
  1581. entry = self.declare(name, cname, type, pos, 'private')
  1582. entry.is_variable = 1
  1583. if type.is_pyobject:
  1584. entry.init = "0"
  1585. entry.is_arg = 1
  1586. #entry.borrowed = 1 # Not using borrowed arg refs for now
  1587. self.arg_entries.append(entry)
  1588. return entry
  1589. def declare_var(self, name, type, pos,
  1590. cname = None, visibility = 'private',
  1591. api = 0, in_pxd = 0, is_cdef = 0):
  1592. # Add an entry for a local variable.
  1593. if visibility in ('public', 'readonly'):
  1594. error(pos, "Local variable cannot be declared %s" % visibility)
  1595. entry = Scope.declare_var(self, name, type, pos,
  1596. cname=cname, visibility=visibility,
  1597. api=api, in_pxd=in_pxd, is_cdef=is_cdef)
  1598. if entry.type.declaration_value:
  1599. entry.init = entry.type.declaration_value
  1600. entry.is_local = 1
  1601. entry.in_with_gil_block = self._in_with_gil_block
  1602. self.var_entries.append(entry)
  1603. return entry
  1604. def declare_global(self, name, pos):
  1605. # Pull entry from global scope into local scope.
  1606. if self.lookup_here(name):
  1607. warning(pos, "'%s' redeclared ", 0)
  1608. else:
  1609. entry = self.global_scope().lookup_target(name)
  1610. self.entries[name] = entry
  1611. def declare_nonlocal(self, name, pos):
  1612. # Pull entry from outer scope into local scope
  1613. orig_entry = self.lookup_here(name)
  1614. if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
  1615. error(pos, "'%s' redeclared as nonlocal" % name)
  1616. orig_entry.already_declared_here()
  1617. else:
  1618. entry = self.lookup(name)
  1619. if entry is None or not entry.from_closure:
  1620. error(pos, "no binding for nonlocal '%s' found" % name)
  1621. def lookup(self, name):
  1622. # Look up name in this scope or an enclosing one.
  1623. # Return None if not found.
  1624. entry = Scope.lookup(self, name)
  1625. if entry is not None:
  1626. entry_scope = entry.scope
  1627. while entry_scope.is_genexpr_scope:
  1628. entry_scope = entry_scope.outer_scope
  1629. if entry_scope is not self and entry_scope.is_closure_scope:
  1630. if hasattr(entry.scope, "scope_class"):
  1631. raise InternalError("lookup() after scope class created.")
  1632. # The actual c fragment for the different scopes differs
  1633. # on the outside and inside, so we make a new entry
  1634. entry.in_closure = True
  1635. inner_entry = InnerEntry(entry, self)
  1636. inner_entry.is_variable = True
  1637. self.entries[name] = inner_entry
  1638. return inner_entry
  1639. return entry
  1640. def mangle_closure_cnames(self, outer_scope_cname):
  1641. for scope in self.iter_local_scopes():
  1642. for entry in scope.entries.values():
  1643. if entry.from_closure:
  1644. cname = entry.outer_entry.cname
  1645. if self.is_passthrough:
  1646. entry.cname = cname
  1647. else:
  1648. if cname.startswith(Naming.cur_scope_cname):
  1649. cname = cname[len(Naming.cur_scope_cname)+2:]
  1650. entry.cname = "%s->%s" % (outer_scope_cname, cname)
  1651. elif entry.in_closure:
  1652. entry.original_cname = entry.cname
  1653. entry.cname = "%s->%s" % (Naming.cur_scope_cname, entry.cname)
  1654. class GeneratorExpressionScope(Scope):
  1655. """Scope for generator expressions and comprehensions. As opposed
  1656. to generators, these can be easily inlined in some cases, so all
  1657. we really need is a scope that holds the loop variable(s).
  1658. """
  1659. is_genexpr_scope = True
  1660. def __init__(self, outer_scope):
  1661. parent_scope = outer_scope
  1662. # TODO: also ignore class scopes?
  1663. while parent_scope.is_genexpr_scope:
  1664. parent_scope = parent_scope.parent_scope
  1665. name = parent_scope.global_scope().next_id(Naming.genexpr_id_ref)
  1666. Scope.__init__(self, name, outer_scope, parent_scope)
  1667. self.directives = outer_scope.directives
  1668. self.genexp_prefix = "%s%d%s" % (Naming.pyrex_prefix, len(name), name)
  1669. # Class/ExtType scopes are filled at class creation time, i.e. from the
  1670. # module init function or surrounding function.
  1671. while outer_scope.is_genexpr_scope or outer_scope.is_c_class_scope or outer_scope.is_py_class_scope:
  1672. outer_scope = outer_scope.outer_scope
  1673. self.var_entries = outer_scope.var_entries # keep declarations outside
  1674. outer_scope.subscopes.add(self)
  1675. def mangle(self, prefix, name):
  1676. return '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(prefix, name))
  1677. def declare_var(self, name, type, pos,
  1678. cname = None, visibility = 'private',
  1679. api = 0, in_pxd = 0, is_cdef = True):
  1680. if type is unspecified_type:
  1681. # if the outer scope defines a type for this variable, inherit it
  1682. outer_entry = self.outer_scope.lookup(name)
  1683. if outer_entry and outer_entry.is_variable:
  1684. type = outer_entry.type # may still be 'unspecified_type' !
  1685. # the parent scope needs to generate code for the variable, but
  1686. # this scope must hold its name exclusively
  1687. cname = '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(Naming.var_prefix, name or self.next_id()))
  1688. entry = self.declare(name, cname, type, pos, visibility)
  1689. entry.is_variable = True
  1690. if self.parent_scope.is_module_scope:
  1691. entry.is_cglobal = True
  1692. else:
  1693. entry.is_local = True
  1694. entry.in_subscope = True
  1695. self.var_entries.append(entry)
  1696. self.entries[name] = entry
  1697. return entry
  1698. def declare_pyfunction(self, name, pos, allow_redefine=False):
  1699. return self.outer_scope.declare_pyfunction(
  1700. name, pos, allow_redefine)
  1701. def declare_lambda_function(self, func_cname, pos):
  1702. return self.outer_scope.declare_lambda_function(func_cname, pos)
  1703. def add_lambda_def(self, def_node):
  1704. return self.outer_scope.add_lambda_def(def_node)
  1705. class ClosureScope(LocalScope):
  1706. is_closure_scope = True
  1707. def __init__(self, name, scope_name, outer_scope, parent_scope=None):
  1708. LocalScope.__init__(self, name, outer_scope, parent_scope)
  1709. self.closure_cname = "%s%s" % (Naming.closure_scope_prefix, scope_name)
  1710. # def mangle_closure_cnames(self, scope_var):
  1711. # for entry in self.entries.values() + self.temp_entries:
  1712. # entry.in_closure = 1
  1713. # LocalScope.mangle_closure_cnames(self, scope_var)
  1714. # def mangle(self, prefix, name):
  1715. # return "%s->%s" % (self.cur_scope_cname, name)
  1716. # return "%s->%s" % (self.closure_cname, name)
  1717. def declare_pyfunction(self, name, pos, allow_redefine=False):
  1718. return LocalScope.declare_pyfunction(self, name, pos, allow_redefine, visibility='private')
  1719. class StructOrUnionScope(Scope):
  1720. # Namespace of a C struct or union.
  1721. def __init__(self, name="?"):
  1722. Scope.__init__(self, name, None, None)
  1723. def declare_var(self, name, type, pos,
  1724. cname = None, visibility = 'private',
  1725. api = 0, in_pxd = 0, is_cdef = 0,
  1726. allow_pyobject=False, allow_memoryview=False):
  1727. # Add an entry for an attribute.
  1728. if not cname:
  1729. cname = name
  1730. if visibility == 'private':
  1731. cname = c_safe_identifier(cname)
  1732. if type.is_cfunction:
  1733. type = PyrexTypes.CPtrType(type)
  1734. entry = self.declare(name, cname, type, pos, visibility)
  1735. entry.is_variable = 1
  1736. self.var_entries.append(entry)
  1737. if type.is_pyobject and not allow_pyobject:
  1738. error(pos, "C struct/union member cannot be a Python object")
  1739. elif type.is_memoryviewslice and not allow_memoryview:
  1740. # Memory views wrap their buffer owner as a Python object.
  1741. error(pos, "C struct/union member cannot be a memory view")
  1742. if visibility != 'private':
  1743. error(pos, "C struct/union member cannot be declared %s" % visibility)
  1744. return entry
  1745. def declare_cfunction(self, name, type, pos,
  1746. cname=None, visibility='private', api=0, in_pxd=0,
  1747. defining=0, modifiers=(), overridable=False): # currently no utility code ...
  1748. if overridable:
  1749. error(pos, "C struct/union member cannot be declared 'cpdef'")
  1750. return self.declare_var(name, type, pos,
  1751. cname=cname, visibility=visibility)
  1752. class ClassScope(Scope):
  1753. # Abstract base class for namespace of
  1754. # Python class or extension type.
  1755. #
  1756. # class_name string Python name of the class
  1757. # scope_prefix string Additional prefix for names
  1758. # declared in the class
  1759. # doc string or None Doc string
  1760. def __init__(self, name, outer_scope):
  1761. Scope.__init__(self, name, outer_scope, outer_scope)
  1762. self.class_name = name
  1763. self.doc = None
  1764. def lookup(self, name):
  1765. entry = Scope.lookup(self, name)
  1766. if entry:
  1767. return entry
  1768. if name == "classmethod":
  1769. # We don't want to use the builtin classmethod here 'cause it won't do the
  1770. # right thing in this scope (as the class members aren't still functions).
  1771. # Don't want to add a cfunction to this scope 'cause that would mess with
  1772. # the type definition, so we just return the right entry.
  1773. entry = Entry(
  1774. "classmethod",
  1775. "__Pyx_Method_ClassMethod",
  1776. PyrexTypes.CFuncType(
  1777. py_object_type,
  1778. [PyrexTypes.CFuncTypeArg("", py_object_type, None)], 0, 0))
  1779. entry.utility_code_definition = Code.UtilityCode.load_cached("ClassMethod", "CythonFunction.c")
  1780. self.use_entry_utility_code(entry)
  1781. entry.is_cfunction = 1
  1782. return entry
  1783. class PyClassScope(ClassScope):
  1784. # Namespace of a Python class.
  1785. #
  1786. # class_obj_cname string C variable holding class object
  1787. is_py_class_scope = 1
  1788. def mangle_class_private_name(self, name):
  1789. return self.mangle_special_name(name)
  1790. def mangle_special_name(self, name):
  1791. if name and name.startswith('__') and not name.endswith('__'):
  1792. name = EncodedString('_%s%s' % (self.class_name.lstrip('_'), name))
  1793. return name
  1794. def lookup_here(self, name):
  1795. name = self.mangle_special_name(name)
  1796. return ClassScope.lookup_here(self, name)
  1797. def declare_var(self, name, type, pos,
  1798. cname = None, visibility = 'private',
  1799. api = 0, in_pxd = 0, is_cdef = 0):
  1800. name = self.mangle_special_name(name)
  1801. if type is unspecified_type:
  1802. type = py_object_type
  1803. # Add an entry for a class attribute.
  1804. entry = Scope.declare_var(self, name, type, pos,
  1805. cname=cname, visibility=visibility,
  1806. api=api, in_pxd=in_pxd, is_cdef=is_cdef)
  1807. entry.is_pyglobal = 1
  1808. entry.is_pyclass_attr = 1
  1809. return entry
  1810. def declare_nonlocal(self, name, pos):
  1811. # Pull entry from outer scope into local scope
  1812. orig_entry = self.lookup_here(name)
  1813. if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
  1814. error(pos, "'%s' redeclared as nonlocal" % name)
  1815. orig_entry.already_declared_here()
  1816. else:
  1817. entry = self.lookup(name)
  1818. if entry is None:
  1819. error(pos, "no binding for nonlocal '%s' found" % name)
  1820. else:
  1821. # FIXME: this works, but it's unclear if it's the
  1822. # right thing to do
  1823. self.entries[name] = entry
  1824. def declare_global(self, name, pos):
  1825. # Pull entry from global scope into local scope.
  1826. if self.lookup_here(name):
  1827. warning(pos, "'%s' redeclared ", 0)
  1828. else:
  1829. entry = self.global_scope().lookup_target(name)
  1830. self.entries[name] = entry
  1831. def add_default_value(self, type):
  1832. return self.outer_scope.add_default_value(type)
  1833. class CClassScope(ClassScope):
  1834. # Namespace of an extension type.
  1835. #
  1836. # parent_type CClassType
  1837. # #typeobj_cname string or None
  1838. # #objstruct_cname string
  1839. # method_table_cname string
  1840. # getset_table_cname string
  1841. # has_pyobject_attrs boolean Any PyObject attributes?
  1842. # has_memoryview_attrs boolean Any memory view attributes?
  1843. # has_cpp_class_attrs boolean Any (non-pointer) C++ attributes?
  1844. # has_cyclic_pyobject_attrs boolean Any PyObject attributes that may need GC?
  1845. # property_entries [Entry]
  1846. # defined boolean Defined in .pxd file
  1847. # implemented boolean Defined in .pyx file
  1848. # inherited_var_entries [Entry] Adapted var entries from base class
  1849. is_c_class_scope = 1
  1850. is_closure_class_scope = False
  1851. has_pyobject_attrs = False
  1852. has_memoryview_attrs = False
  1853. has_cpp_class_attrs = False
  1854. has_cyclic_pyobject_attrs = False
  1855. defined = False
  1856. implemented = False
  1857. def __init__(self, name, outer_scope, visibility):
  1858. ClassScope.__init__(self, name, outer_scope)
  1859. if visibility != 'extern':
  1860. self.method_table_cname = outer_scope.mangle(Naming.methtab_prefix, name)
  1861. self.getset_table_cname = outer_scope.mangle(Naming.gstab_prefix, name)
  1862. self.property_entries = []
  1863. self.inherited_var_entries = []
  1864. def needs_gc(self):
  1865. # If the type or any of its base types have Python-valued
  1866. # C attributes, then it needs to participate in GC.
  1867. if self.has_cyclic_pyobject_attrs and not self.directives.get('no_gc', False):
  1868. return True
  1869. base_type = self.parent_type.base_type
  1870. if base_type and base_type.scope is not None:
  1871. return base_type.scope.needs_gc()
  1872. elif self.parent_type.is_builtin_type:
  1873. return not self.parent_type.is_gc_simple
  1874. return False
  1875. def needs_tp_clear(self):
  1876. """
  1877. Do we need to generate an implementation for the tp_clear slot? Can
  1878. be disabled to keep references for the __dealloc__ cleanup function.
  1879. """
  1880. return self.needs_gc() and not self.directives.get('no_gc_clear', False)
  1881. def get_refcounted_entries(self, include_weakref=False,
  1882. include_gc_simple=True):
  1883. py_attrs = []
  1884. py_buffers = []
  1885. memoryview_slices = []
  1886. for entry in self.var_entries:
  1887. if entry.type.is_pyobject:
  1888. if include_weakref or (self.is_closure_class_scope or entry.name != "__weakref__"):
  1889. if include_gc_simple or not entry.type.is_gc_simple:
  1890. py_attrs.append(entry)
  1891. elif entry.type == PyrexTypes.c_py_buffer_type:
  1892. py_buffers.append(entry)
  1893. elif entry.type.is_memoryviewslice:
  1894. memoryview_slices.append(entry)
  1895. have_entries = py_attrs or py_buffers or memoryview_slices
  1896. return have_entries, (py_attrs, py_buffers, memoryview_slices)
  1897. def declare_var(self, name, type, pos,
  1898. cname = None, visibility = 'private',
  1899. api = 0, in_pxd = 0, is_cdef = 0):
  1900. if is_cdef:
  1901. # Add an entry for an attribute.
  1902. if self.defined:
  1903. error(pos,
  1904. "C attributes cannot be added in implementation part of"
  1905. " extension type defined in a pxd")
  1906. if not self.is_closure_class_scope and get_special_method_signature(name):
  1907. error(pos,
  1908. "The name '%s' is reserved for a special method."
  1909. % name)
  1910. if not cname:
  1911. cname = name
  1912. if visibility == 'private':
  1913. cname = c_safe_identifier(cname)
  1914. if type.is_cpp_class and visibility != 'extern':
  1915. type.check_nullary_constructor(pos)
  1916. self.use_utility_code(Code.UtilityCode("#include <new>"))
  1917. entry = self.declare(name, cname, type, pos, visibility)
  1918. entry.is_variable = 1
  1919. self.var_entries.append(entry)
  1920. if type.is_memoryviewslice:
  1921. self.has_memoryview_attrs = True
  1922. elif type.is_cpp_class:
  1923. self.has_cpp_class_attrs = True
  1924. elif type.is_pyobject and (self.is_closure_class_scope or name != '__weakref__'):
  1925. self.has_pyobject_attrs = True
  1926. if (not type.is_builtin_type
  1927. or not type.scope or type.scope.needs_gc()):
  1928. self.has_cyclic_pyobject_attrs = True
  1929. if visibility not in ('private', 'public', 'readonly'):
  1930. error(pos,
  1931. "Attribute of extension type cannot be declared %s" % visibility)
  1932. if visibility in ('public', 'readonly'):
  1933. # If the field is an external typedef, we cannot be sure about the type,
  1934. # so do conversion ourself rather than rely on the CPython mechanism (through
  1935. # a property; made in AnalyseDeclarationsTransform).
  1936. entry.needs_property = True
  1937. if not self.is_closure_class_scope and name == "__weakref__":
  1938. error(pos, "Special attribute __weakref__ cannot be exposed to Python")
  1939. if not (type.is_pyobject or type.can_coerce_to_pyobject(self)):
  1940. # we're not testing for coercion *from* Python here - that would fail later
  1941. error(pos, "C attribute of type '%s' cannot be accessed from Python" % type)
  1942. else:
  1943. entry.needs_property = False
  1944. return entry
  1945. else:
  1946. if type is unspecified_type:
  1947. type = py_object_type
  1948. # Add an entry for a class attribute.
  1949. entry = Scope.declare_var(self, name, type, pos,
  1950. cname=cname, visibility=visibility,
  1951. api=api, in_pxd=in_pxd, is_cdef=is_cdef)
  1952. entry.is_member = 1
  1953. entry.is_pyglobal = 1 # xxx: is_pyglobal changes behaviour in so many places that
  1954. # I keep it in for now. is_member should be enough
  1955. # later on
  1956. self.namespace_cname = "(PyObject *)%s" % self.parent_type.typeptr_cname
  1957. return entry
  1958. def declare_pyfunction(self, name, pos, allow_redefine=False):
  1959. # Add an entry for a method.
  1960. if name in richcmp_special_methods:
  1961. if self.lookup_here('__richcmp__'):
  1962. error(pos, "Cannot define both % and __richcmp__" % name)
  1963. elif name == '__richcmp__':
  1964. for n in richcmp_special_methods:
  1965. if self.lookup_here(n):
  1966. error(pos, "Cannot define both % and __richcmp__" % n)
  1967. if name == "__new__":
  1968. error(pos, "__new__ method of extension type will change semantics "
  1969. "in a future version of Pyrex and Cython. Use __cinit__ instead.")
  1970. entry = self.declare_var(name, py_object_type, pos,
  1971. visibility='extern')
  1972. special_sig = get_special_method_signature(name)
  1973. if special_sig:
  1974. # Special methods get put in the method table with a particular
  1975. # signature declared in advance.
  1976. entry.signature = special_sig
  1977. entry.is_special = 1
  1978. else:
  1979. entry.signature = pymethod_signature
  1980. entry.is_special = 0
  1981. self.pyfunc_entries.append(entry)
  1982. return entry
  1983. def lookup_here(self, name):
  1984. if not self.is_closure_class_scope and name == "__new__":
  1985. name = EncodedString("__cinit__")
  1986. entry = ClassScope.lookup_here(self, name)
  1987. if entry and entry.is_builtin_cmethod:
  1988. if not self.parent_type.is_builtin_type:
  1989. # For subtypes of builtin types, we can only return
  1990. # optimised C methods if the type if final.
  1991. # Otherwise, subtypes may choose to override the
  1992. # method, but the optimisation would prevent the
  1993. # subtype method from being called.
  1994. if not self.parent_type.is_final_type:
  1995. return None
  1996. return entry
  1997. def declare_cfunction(self, name, type, pos,
  1998. cname=None, visibility='private', api=0, in_pxd=0,
  1999. defining=0, modifiers=(), utility_code=None, overridable=False):
  2000. if get_special_method_signature(name) and not self.parent_type.is_builtin_type:
  2001. error(pos, "Special methods must be declared with 'def', not 'cdef'")
  2002. args = type.args
  2003. if not type.is_static_method:
  2004. if not args:
  2005. error(pos, "C method has no self argument")
  2006. elif not self.parent_type.assignable_from(args[0].type):
  2007. error(pos, "Self argument (%s) of C method '%s' does not match parent type (%s)" %
  2008. (args[0].type, name, self.parent_type))
  2009. entry = self.lookup_here(name)
  2010. if cname is None:
  2011. cname = c_safe_identifier(name)
  2012. if entry:
  2013. if not entry.is_cfunction:
  2014. warning(pos, "'%s' redeclared " % name, 0)
  2015. else:
  2016. if defining and entry.func_cname:
  2017. error(pos, "'%s' already defined" % name)
  2018. #print "CClassScope.declare_cfunction: checking signature" ###
  2019. if entry.is_final_cmethod and entry.is_inherited:
  2020. error(pos, "Overriding final methods is not allowed")
  2021. elif type.same_c_signature_as(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
  2022. # Fix with_gil vs nogil.
  2023. entry.type = entry.type.with_with_gil(type.with_gil)
  2024. elif type.compatible_signature_with(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
  2025. if (self.defined and not in_pxd
  2026. and not type.same_c_signature_as_resolved_type(entry.type, as_cmethod = 1, as_pxd_definition = 1)):
  2027. # TODO(robertwb): Make this an error.
  2028. warning(pos,
  2029. "Compatible but non-identical C method '%s' not redeclared "
  2030. "in definition part of extension type '%s'. "
  2031. "This may cause incorrect vtables to be generated." % (
  2032. name, self.class_name), 2)
  2033. warning(entry.pos, "Previous declaration is here", 2)
  2034. entry = self.add_cfunction(name, type, pos, cname, visibility='ignore', modifiers=modifiers)
  2035. else:
  2036. error(pos, "Signature not compatible with previous declaration")
  2037. error(entry.pos, "Previous declaration is here")
  2038. else:
  2039. if self.defined:
  2040. error(pos,
  2041. "C method '%s' not previously declared in definition part of"
  2042. " extension type '%s'" % (name, self.class_name))
  2043. entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
  2044. if defining:
  2045. entry.func_cname = self.mangle(Naming.func_prefix, name)
  2046. entry.utility_code = utility_code
  2047. type.entry = entry
  2048. if u'inline' in modifiers:
  2049. entry.is_inline_cmethod = True
  2050. if (self.parent_type.is_final_type or entry.is_inline_cmethod or
  2051. self.directives.get('final')):
  2052. entry.is_final_cmethod = True
  2053. entry.final_func_cname = entry.func_cname
  2054. return entry
  2055. def add_cfunction(self, name, type, pos, cname, visibility, modifiers, inherited=False):
  2056. # Add a cfunction entry without giving it a func_cname.
  2057. prev_entry = self.lookup_here(name)
  2058. entry = ClassScope.add_cfunction(self, name, type, pos, cname,
  2059. visibility, modifiers, inherited=inherited)
  2060. entry.is_cmethod = 1
  2061. entry.prev_entry = prev_entry
  2062. return entry
  2063. def declare_builtin_cfunction(self, name, type, cname, utility_code = None):
  2064. # overridden methods of builtin types still have their Python
  2065. # equivalent that must be accessible to support bound methods
  2066. name = EncodedString(name)
  2067. entry = self.declare_cfunction(name, type, None, cname, visibility='extern',
  2068. utility_code=utility_code)
  2069. var_entry = Entry(name, name, py_object_type)
  2070. var_entry.qualified_name = name
  2071. var_entry.is_variable = 1
  2072. var_entry.is_builtin = 1
  2073. var_entry.utility_code = utility_code
  2074. var_entry.scope = entry.scope
  2075. entry.as_variable = var_entry
  2076. return entry
  2077. def declare_property(self, name, doc, pos):
  2078. entry = self.lookup_here(name)
  2079. if entry is None:
  2080. entry = self.declare(name, name, py_object_type, pos, 'private')
  2081. entry.is_property = 1
  2082. entry.doc = doc
  2083. entry.scope = PropertyScope(name,
  2084. outer_scope = self.global_scope(), parent_scope = self)
  2085. entry.scope.parent_type = self.parent_type
  2086. self.property_entries.append(entry)
  2087. return entry
  2088. def declare_inherited_c_attributes(self, base_scope):
  2089. # Declare entries for all the C attributes of an
  2090. # inherited type, with cnames modified appropriately
  2091. # to work with this type.
  2092. def adapt(cname):
  2093. return "%s.%s" % (Naming.obj_base_cname, base_entry.cname)
  2094. entries = base_scope.inherited_var_entries + base_scope.var_entries
  2095. for base_entry in entries:
  2096. entry = self.declare(
  2097. base_entry.name, adapt(base_entry.cname),
  2098. base_entry.type, None, 'private')
  2099. entry.is_variable = 1
  2100. self.inherited_var_entries.append(entry)
  2101. # If the class defined in a pxd, specific entries have not been added.
  2102. # Ensure now that the parent (base) scope has specific entries
  2103. # Iterate over a copy as get_all_specialized_function_types() will mutate
  2104. for base_entry in base_scope.cfunc_entries[:]:
  2105. if base_entry.type.is_fused:
  2106. base_entry.type.get_all_specialized_function_types()
  2107. for base_entry in base_scope.cfunc_entries:
  2108. cname = base_entry.cname
  2109. var_entry = base_entry.as_variable
  2110. is_builtin = var_entry and var_entry.is_builtin
  2111. if not is_builtin:
  2112. cname = adapt(cname)
  2113. entry = self.add_cfunction(base_entry.name, base_entry.type,
  2114. base_entry.pos, cname,
  2115. base_entry.visibility, base_entry.func_modifiers, inherited=True)
  2116. entry.is_inherited = 1
  2117. if base_entry.is_final_cmethod:
  2118. entry.is_final_cmethod = True
  2119. entry.is_inline_cmethod = base_entry.is_inline_cmethod
  2120. if (self.parent_scope == base_scope.parent_scope or
  2121. entry.is_inline_cmethod):
  2122. entry.final_func_cname = base_entry.final_func_cname
  2123. if is_builtin:
  2124. entry.is_builtin_cmethod = True
  2125. entry.as_variable = var_entry
  2126. if base_entry.utility_code:
  2127. entry.utility_code = base_entry.utility_code
  2128. class CppClassScope(Scope):
  2129. # Namespace of a C++ class.
  2130. is_cpp_class_scope = 1
  2131. default_constructor = None
  2132. type = None
  2133. def __init__(self, name, outer_scope, templates=None):
  2134. Scope.__init__(self, name, outer_scope, None)
  2135. self.directives = outer_scope.directives
  2136. self.inherited_var_entries = []
  2137. if templates is not None:
  2138. for T in templates:
  2139. template_entry = self.declare(
  2140. T, T, PyrexTypes.TemplatePlaceholderType(T), None, 'extern')
  2141. template_entry.is_type = 1
  2142. def declare_var(self, name, type, pos,
  2143. cname = None, visibility = 'extern',
  2144. api = 0, in_pxd = 0, is_cdef = 0, defining = 0):
  2145. # Add an entry for an attribute.
  2146. if not cname:
  2147. cname = name
  2148. entry = self.lookup_here(name)
  2149. if defining and entry is not None:
  2150. if entry.type.same_as(type):
  2151. # Fix with_gil vs nogil.
  2152. entry.type = entry.type.with_with_gil(type.with_gil)
  2153. elif type.is_cfunction and type.compatible_signature_with(entry.type):
  2154. entry.type = type
  2155. else:
  2156. error(pos, "Function signature does not match previous declaration")
  2157. else:
  2158. entry = self.declare(name, cname, type, pos, visibility)
  2159. entry.is_variable = 1
  2160. if type.is_cfunction and self.type:
  2161. if not self.type.get_fused_types():
  2162. entry.func_cname = "%s::%s" % (self.type.empty_declaration_code(), cname)
  2163. if name != "this" and (defining or name != "<init>"):
  2164. self.var_entries.append(entry)
  2165. return entry
  2166. def declare_cfunction(self, name, type, pos,
  2167. cname=None, visibility='extern', api=0, in_pxd=0,
  2168. defining=0, modifiers=(), utility_code=None, overridable=False):
  2169. class_name = self.name.split('::')[-1]
  2170. if name in (class_name, '__init__') and cname is None:
  2171. cname = "%s__init__%s" % (Naming.func_prefix, class_name)
  2172. name = '<init>'
  2173. type.return_type = PyrexTypes.CVoidType()
  2174. # This is called by the actual constructor, but need to support
  2175. # arguments that cannot by called by value.
  2176. type.original_args = type.args
  2177. def maybe_ref(arg):
  2178. if arg.type.is_cpp_class and not arg.type.is_reference:
  2179. return PyrexTypes.CFuncTypeArg(
  2180. arg.name, PyrexTypes.c_ref_type(arg.type), arg.pos)
  2181. else:
  2182. return arg
  2183. type.args = [maybe_ref(arg) for arg in type.args]
  2184. elif name == '__dealloc__' and cname is None:
  2185. cname = "%s__dealloc__%s" % (Naming.func_prefix, class_name)
  2186. name = '<del>'
  2187. type.return_type = PyrexTypes.CVoidType()
  2188. if name in ('<init>', '<del>') and type.nogil:
  2189. for base in self.type.base_classes:
  2190. base_entry = base.scope.lookup(name)
  2191. if base_entry and not base_entry.type.nogil:
  2192. error(pos, "Constructor cannot be called without GIL unless all base constructors can also be called without GIL")
  2193. error(base_entry.pos, "Base constructor defined here.")
  2194. prev_entry = self.lookup_here(name)
  2195. entry = self.declare_var(name, type, pos,
  2196. defining=defining,
  2197. cname=cname, visibility=visibility)
  2198. if prev_entry and not defining:
  2199. entry.overloaded_alternatives = prev_entry.all_alternatives()
  2200. entry.utility_code = utility_code
  2201. type.entry = entry
  2202. return entry
  2203. def declare_inherited_cpp_attributes(self, base_class):
  2204. base_scope = base_class.scope
  2205. template_type = base_class
  2206. while getattr(template_type, 'template_type', None):
  2207. template_type = template_type.template_type
  2208. if getattr(template_type, 'templates', None):
  2209. base_templates = [T.name for T in template_type.templates]
  2210. else:
  2211. base_templates = ()
  2212. # Declare entries for all the C++ attributes of an
  2213. # inherited type, with cnames modified appropriately
  2214. # to work with this type.
  2215. for base_entry in \
  2216. base_scope.inherited_var_entries + base_scope.var_entries:
  2217. #constructor/destructor is not inherited
  2218. if base_entry.name in ("<init>", "<del>"):
  2219. continue
  2220. #print base_entry.name, self.entries
  2221. if base_entry.name in self.entries:
  2222. base_entry.name # FIXME: is there anything to do in this case?
  2223. entry = self.declare(base_entry.name, base_entry.cname,
  2224. base_entry.type, None, 'extern')
  2225. entry.is_variable = 1
  2226. entry.is_inherited = 1
  2227. self.inherited_var_entries.append(entry)
  2228. for base_entry in base_scope.cfunc_entries:
  2229. entry = self.declare_cfunction(base_entry.name, base_entry.type,
  2230. base_entry.pos, base_entry.cname,
  2231. base_entry.visibility, api=0,
  2232. modifiers=base_entry.func_modifiers,
  2233. utility_code=base_entry.utility_code)
  2234. entry.is_inherited = 1
  2235. for base_entry in base_scope.type_entries:
  2236. if base_entry.name not in base_templates:
  2237. entry = self.declare_type(base_entry.name, base_entry.type,
  2238. base_entry.pos, base_entry.cname,
  2239. base_entry.visibility)
  2240. entry.is_inherited = 1
  2241. def specialize(self, values, type_entry):
  2242. scope = CppClassScope(self.name, self.outer_scope)
  2243. scope.type = type_entry
  2244. for entry in self.entries.values():
  2245. if entry.is_type:
  2246. scope.declare_type(entry.name,
  2247. entry.type.specialize(values),
  2248. entry.pos,
  2249. entry.cname,
  2250. template=1)
  2251. elif entry.type.is_cfunction:
  2252. for e in entry.all_alternatives():
  2253. scope.declare_cfunction(e.name,
  2254. e.type.specialize(values),
  2255. e.pos,
  2256. e.cname,
  2257. utility_code=e.utility_code)
  2258. else:
  2259. scope.declare_var(entry.name,
  2260. entry.type.specialize(values),
  2261. entry.pos,
  2262. entry.cname,
  2263. entry.visibility)
  2264. return scope
  2265. class PropertyScope(Scope):
  2266. # Scope holding the __get__, __set__ and __del__ methods for
  2267. # a property of an extension type.
  2268. #
  2269. # parent_type PyExtensionType The type to which the property belongs
  2270. is_property_scope = 1
  2271. def declare_pyfunction(self, name, pos, allow_redefine=False):
  2272. # Add an entry for a method.
  2273. signature = get_property_accessor_signature(name)
  2274. if signature:
  2275. entry = self.declare(name, name, py_object_type, pos, 'private')
  2276. entry.is_special = 1
  2277. entry.signature = signature
  2278. return entry
  2279. else:
  2280. error(pos, "Only __get__, __set__ and __del__ methods allowed "
  2281. "in a property declaration")
  2282. return None
  2283. class CConstScope(Scope):
  2284. def __init__(self, const_base_type_scope):
  2285. Scope.__init__(
  2286. self,
  2287. 'const_' + const_base_type_scope.name,
  2288. const_base_type_scope.outer_scope,
  2289. const_base_type_scope.parent_scope)
  2290. self.const_base_type_scope = const_base_type_scope
  2291. def lookup_here(self, name):
  2292. entry = self.const_base_type_scope.lookup_here(name)
  2293. if entry is not None:
  2294. entry = copy.copy(entry)
  2295. entry.type = PyrexTypes.c_const_type(entry.type)
  2296. return entry
  2297. class TemplateScope(Scope):
  2298. def __init__(self, name, outer_scope):
  2299. Scope.__init__(self, name, outer_scope, None)
  2300. self.directives = outer_scope.directives