ModuleNode.py 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  1. #
  2. # Module parse tree node
  3. #
  4. from __future__ import absolute_import
  5. import cython
  6. cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object,
  7. error=object, warning=object, py_object_type=object, UtilityCode=object,
  8. EncodedString=object, re=object)
  9. from collections import defaultdict
  10. import json
  11. import operator
  12. import os
  13. import re
  14. from .PyrexTypes import CPtrType
  15. from . import Future
  16. from . import Annotate
  17. from . import Code
  18. from . import Naming
  19. from . import Nodes
  20. from . import Options
  21. from . import TypeSlots
  22. from . import PyrexTypes
  23. from . import Pythran
  24. from .Errors import error, warning
  25. from .PyrexTypes import py_object_type
  26. from ..Utils import open_new_file, replace_suffix, decode_filename, build_hex_version
  27. from .Code import UtilityCode, IncludeCode
  28. from .StringEncoding import EncodedString
  29. from .Pythran import has_np_pythran
  30. def check_c_declarations_pxd(module_node):
  31. module_node.scope.check_c_classes_pxd()
  32. return module_node
  33. def check_c_declarations(module_node):
  34. module_node.scope.check_c_classes()
  35. module_node.scope.check_c_functions()
  36. return module_node
  37. def generate_c_code_config(env, options):
  38. if Options.annotate or options.annotate:
  39. emit_linenums = False
  40. else:
  41. emit_linenums = options.emit_linenums
  42. return Code.CCodeConfig(
  43. emit_linenums=emit_linenums,
  44. emit_code_comments=env.directives['emit_code_comments'],
  45. c_line_in_traceback=options.c_line_in_traceback)
  46. class ModuleNode(Nodes.Node, Nodes.BlockNode):
  47. # doc string or None
  48. # body StatListNode
  49. #
  50. # referenced_modules [ModuleScope]
  51. # full_module_name string
  52. #
  53. # scope The module scope.
  54. # compilation_source A CompilationSource (see Main)
  55. # directives Top-level compiler directives
  56. child_attrs = ["body"]
  57. directives = None
  58. def merge_in(self, tree, scope, merge_scope=False):
  59. # Merges in the contents of another tree, and possibly scope. With the
  60. # current implementation below, this must be done right prior
  61. # to code generation.
  62. #
  63. # Note: This way of doing it seems strange -- I believe the
  64. # right concept is to split ModuleNode into a ModuleNode and a
  65. # CodeGenerator, and tell that CodeGenerator to generate code
  66. # from multiple sources.
  67. assert isinstance(self.body, Nodes.StatListNode)
  68. if isinstance(tree, Nodes.StatListNode):
  69. self.body.stats.extend(tree.stats)
  70. else:
  71. self.body.stats.append(tree)
  72. self.scope.utility_code_list.extend(scope.utility_code_list)
  73. for inc in scope.c_includes.values():
  74. self.scope.process_include(inc)
  75. def extend_if_not_in(L1, L2):
  76. for x in L2:
  77. if x not in L1:
  78. L1.append(x)
  79. extend_if_not_in(self.scope.included_files, scope.included_files)
  80. if merge_scope:
  81. # Ensure that we don't generate import code for these entries!
  82. for entry in scope.c_class_entries:
  83. entry.type.module_name = self.full_module_name
  84. entry.type.scope.directives["internal"] = True
  85. self.scope.merge_in(scope)
  86. def analyse_declarations(self, env):
  87. if has_np_pythran(env):
  88. Pythran.include_pythran_generic(env)
  89. if self.directives:
  90. env.old_style_globals = self.directives['old_style_globals']
  91. if not Options.docstrings:
  92. env.doc = self.doc = None
  93. elif Options.embed_pos_in_docstring:
  94. env.doc = EncodedString(u'File: %s (starting at line %s)' % Nodes.relative_position(self.pos))
  95. if self.doc is not None:
  96. env.doc = EncodedString(env.doc + u'\n' + self.doc)
  97. env.doc.encoding = self.doc.encoding
  98. else:
  99. env.doc = self.doc
  100. env.directives = self.directives
  101. self.body.analyse_declarations(env)
  102. def prepare_utility_code(self):
  103. # prepare any utility code that must be created before code generation
  104. # specifically: CythonUtilityCode
  105. env = self.scope
  106. if env.has_import_star:
  107. self.create_import_star_conversion_utility_code(env)
  108. for name, entry in sorted(env.entries.items()):
  109. if (entry.create_wrapper and entry.scope is env
  110. and entry.is_type and entry.type.is_enum):
  111. entry.type.create_type_wrapper(env)
  112. def process_implementation(self, options, result):
  113. env = self.scope
  114. env.return_type = PyrexTypes.c_void_type
  115. self.referenced_modules = []
  116. self.find_referenced_modules(env, self.referenced_modules, {})
  117. self.sort_cdef_classes(env)
  118. self.generate_c_code(env, options, result)
  119. self.generate_h_code(env, options, result)
  120. self.generate_api_code(env, options, result)
  121. def has_imported_c_functions(self):
  122. for module in self.referenced_modules:
  123. for entry in module.cfunc_entries:
  124. if entry.defined_in_pxd:
  125. return 1
  126. return 0
  127. def generate_h_code(self, env, options, result):
  128. def h_entries(entries, api=0, pxd=0):
  129. return [entry for entry in entries
  130. if ((entry.visibility == 'public') or
  131. (api and entry.api) or
  132. (pxd and entry.defined_in_pxd))]
  133. h_types = h_entries(env.type_entries, api=1)
  134. h_vars = h_entries(env.var_entries)
  135. h_funcs = h_entries(env.cfunc_entries)
  136. h_extension_types = h_entries(env.c_class_entries)
  137. if h_types or h_vars or h_funcs or h_extension_types:
  138. result.h_file = replace_suffix(result.c_file, ".h")
  139. h_code = Code.CCodeWriter()
  140. c_code_config = generate_c_code_config(env, options)
  141. Code.GlobalState(h_code, self, c_code_config)
  142. if options.generate_pxi:
  143. result.i_file = replace_suffix(result.c_file, ".pxi")
  144. i_code = Code.PyrexCodeWriter(result.i_file)
  145. else:
  146. i_code = None
  147. h_code.put_generated_by()
  148. h_guard = Naming.h_guard_prefix + self.api_name(env)
  149. h_code.put_h_guard(h_guard)
  150. h_code.putln("")
  151. h_code.putln('#include "Python.h"')
  152. self.generate_type_header_code(h_types, h_code)
  153. if options.capi_reexport_cincludes:
  154. self.generate_includes(env, [], h_code)
  155. h_code.putln("")
  156. api_guard = Naming.api_guard_prefix + self.api_name(env)
  157. h_code.putln("#ifndef %s" % api_guard)
  158. h_code.putln("")
  159. self.generate_extern_c_macro_definition(h_code)
  160. h_code.putln("")
  161. self.generate_dl_import_macro(h_code)
  162. if h_extension_types:
  163. h_code.putln("")
  164. for entry in h_extension_types:
  165. self.generate_cclass_header_code(entry.type, h_code)
  166. if i_code:
  167. self.generate_cclass_include_code(entry.type, i_code)
  168. if h_funcs:
  169. h_code.putln("")
  170. for entry in h_funcs:
  171. self.generate_public_declaration(entry, h_code, i_code)
  172. if h_vars:
  173. h_code.putln("")
  174. for entry in h_vars:
  175. self.generate_public_declaration(entry, h_code, i_code)
  176. h_code.putln("")
  177. h_code.putln("#endif /* !%s */" % api_guard)
  178. h_code.putln("")
  179. h_code.putln("/* WARNING: the interface of the module init function changed in CPython 3.5. */")
  180. h_code.putln("/* It now returns a PyModuleDef instance instead of a PyModule instance. */")
  181. h_code.putln("")
  182. h_code.putln("#if PY_MAJOR_VERSION < 3")
  183. init_name = 'init' + (options.init_suffix or env.module_name)
  184. h_code.putln("PyMODINIT_FUNC %s(void);" % init_name)
  185. h_code.putln("#else")
  186. h_code.putln("PyMODINIT_FUNC %s(void);" % self.mod_init_func_cname('PyInit', env, options))
  187. h_code.putln("#endif")
  188. h_code.putln("")
  189. h_code.putln("#endif /* !%s */" % h_guard)
  190. f = open_new_file(result.h_file)
  191. try:
  192. h_code.copyto(f)
  193. finally:
  194. f.close()
  195. def generate_public_declaration(self, entry, h_code, i_code):
  196. h_code.putln("%s %s;" % (
  197. Naming.extern_c_macro,
  198. entry.type.declaration_code(entry.cname)))
  199. if i_code:
  200. i_code.putln("cdef extern %s" % (
  201. entry.type.declaration_code(entry.cname, pyrex=1)))
  202. def api_name(self, env):
  203. return env.qualified_name.replace(".", "__")
  204. def generate_api_code(self, env, options, result):
  205. def api_entries(entries, pxd=0):
  206. return [entry for entry in entries
  207. if entry.api or (pxd and entry.defined_in_pxd)]
  208. api_vars = api_entries(env.var_entries)
  209. api_funcs = api_entries(env.cfunc_entries)
  210. api_extension_types = api_entries(env.c_class_entries)
  211. if api_vars or api_funcs or api_extension_types:
  212. result.api_file = replace_suffix(result.c_file, "_api.h")
  213. h_code = Code.CCodeWriter()
  214. c_code_config = generate_c_code_config(env, options)
  215. Code.GlobalState(h_code, self, c_code_config)
  216. h_code.put_generated_by()
  217. api_guard = Naming.api_guard_prefix + self.api_name(env)
  218. h_code.put_h_guard(api_guard)
  219. # Work around https://bugs.python.org/issue4709
  220. h_code.putln('#ifdef __MINGW64__')
  221. h_code.putln('#define MS_WIN64')
  222. h_code.putln('#endif')
  223. h_code.putln('#include "Python.h"')
  224. if result.h_file:
  225. h_code.putln('#include "%s"' % os.path.basename(result.h_file))
  226. if api_extension_types:
  227. h_code.putln("")
  228. for entry in api_extension_types:
  229. type = entry.type
  230. h_code.putln("static PyTypeObject *%s = 0;" % type.typeptr_cname)
  231. h_code.putln("#define %s (*%s)" % (
  232. type.typeobj_cname, type.typeptr_cname))
  233. if api_funcs:
  234. h_code.putln("")
  235. for entry in api_funcs:
  236. type = CPtrType(entry.type)
  237. cname = env.mangle(Naming.func_prefix_api, entry.name)
  238. h_code.putln("static %s = 0;" % type.declaration_code(cname))
  239. h_code.putln("#define %s %s" % (entry.name, cname))
  240. if api_vars:
  241. h_code.putln("")
  242. for entry in api_vars:
  243. type = CPtrType(entry.type)
  244. cname = env.mangle(Naming.varptr_prefix_api, entry.name)
  245. h_code.putln("static %s = 0;" % type.declaration_code(cname))
  246. h_code.putln("#define %s (*%s)" % (entry.name, cname))
  247. h_code.put(UtilityCode.load_as_string("PyIdentifierFromString", "ImportExport.c")[0])
  248. if api_vars:
  249. h_code.put(UtilityCode.load_as_string("VoidPtrImport", "ImportExport.c")[1])
  250. if api_funcs:
  251. h_code.put(UtilityCode.load_as_string("FunctionImport", "ImportExport.c")[1])
  252. if api_extension_types:
  253. h_code.put(UtilityCode.load_as_string("TypeImport", "ImportExport.c")[0])
  254. h_code.put(UtilityCode.load_as_string("TypeImport", "ImportExport.c")[1])
  255. h_code.putln("")
  256. h_code.putln("static int import_%s(void) {" % self.api_name(env))
  257. h_code.putln("PyObject *module = 0;")
  258. h_code.putln('module = PyImport_ImportModule("%s");' % env.qualified_name)
  259. h_code.putln("if (!module) goto bad;")
  260. for entry in api_funcs:
  261. cname = env.mangle(Naming.func_prefix_api, entry.name)
  262. sig = entry.type.signature_string()
  263. h_code.putln(
  264. 'if (__Pyx_ImportFunction_%s(module, "%s", (void (**)(void))&%s, "%s") < 0) goto bad;'
  265. % (Naming.cyversion, entry.name, cname, sig))
  266. for entry in api_vars:
  267. cname = env.mangle(Naming.varptr_prefix_api, entry.name)
  268. sig = entry.type.empty_declaration_code()
  269. h_code.putln(
  270. 'if (__Pyx_ImportVoidPtr_%s(module, "%s", (void **)&%s, "%s") < 0) goto bad;'
  271. % (Naming.cyversion, entry.name, cname, sig))
  272. with ModuleImportGenerator(h_code, imported_modules={env.qualified_name: 'module'}) as import_generator:
  273. for entry in api_extension_types:
  274. self.generate_type_import_call(entry.type, h_code, import_generator, error_code="goto bad;")
  275. h_code.putln("Py_DECREF(module); module = 0;")
  276. h_code.putln("return 0;")
  277. h_code.putln("bad:")
  278. h_code.putln("Py_XDECREF(module);")
  279. h_code.putln("return -1;")
  280. h_code.putln("}")
  281. h_code.putln("")
  282. h_code.putln("#endif /* !%s */" % api_guard)
  283. f = open_new_file(result.api_file)
  284. try:
  285. h_code.copyto(f)
  286. finally:
  287. f.close()
  288. def generate_cclass_header_code(self, type, h_code):
  289. h_code.putln("%s %s %s;" % (
  290. Naming.extern_c_macro,
  291. PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"),
  292. type.typeobj_cname))
  293. def generate_cclass_include_code(self, type, i_code):
  294. i_code.putln("cdef extern class %s.%s:" % (
  295. type.module_name, type.name))
  296. i_code.indent()
  297. var_entries = type.scope.var_entries
  298. if var_entries:
  299. for entry in var_entries:
  300. i_code.putln("cdef %s" % (
  301. entry.type.declaration_code(entry.cname, pyrex=1)))
  302. else:
  303. i_code.putln("pass")
  304. i_code.dedent()
  305. def generate_c_code(self, env, options, result):
  306. modules = self.referenced_modules
  307. if Options.annotate or options.annotate:
  308. rootwriter = Annotate.AnnotationCCodeWriter()
  309. else:
  310. rootwriter = Code.CCodeWriter()
  311. c_code_config = generate_c_code_config(env, options)
  312. globalstate = Code.GlobalState(
  313. rootwriter, self,
  314. code_config=c_code_config,
  315. common_utility_include_dir=options.common_utility_include_dir,
  316. )
  317. globalstate.initialize_main_c_code()
  318. h_code = globalstate['h_code']
  319. self.generate_module_preamble(env, options, modules, result.embedded_metadata, h_code)
  320. globalstate.module_pos = self.pos
  321. globalstate.directives = self.directives
  322. globalstate.use_utility_code(refnanny_utility_code)
  323. code = globalstate['before_global_var']
  324. code.putln('#define __Pyx_MODULE_NAME "%s"' % self.full_module_name)
  325. module_is_main = "%s%s" % (Naming.module_is_main, self.full_module_name.replace('.', '__'))
  326. code.putln("extern int %s;" % module_is_main)
  327. code.putln("int %s = 0;" % module_is_main)
  328. code.putln("")
  329. code.putln("/* Implementation of '%s' */" % env.qualified_name)
  330. code = globalstate['late_includes']
  331. code.putln("/* Late includes */")
  332. self.generate_includes(env, modules, code, early=False)
  333. code = globalstate['all_the_rest']
  334. self.generate_cached_builtins_decls(env, code)
  335. self.generate_lambda_definitions(env, code)
  336. # generate normal variable and function definitions
  337. self.generate_variable_definitions(env, code)
  338. self.body.generate_function_definitions(env, code)
  339. code.mark_pos(None)
  340. self.generate_typeobj_definitions(env, code)
  341. self.generate_method_table(env, code)
  342. if env.has_import_star:
  343. self.generate_import_star(env, code)
  344. self.generate_pymoduledef_struct(env, options, code)
  345. # initialise the macro to reduce the code size of one-time functionality
  346. code.putln(UtilityCode.load_as_string("SmallCodeConfig", "ModuleSetupCode.c")[0].strip())
  347. # init_globals is inserted before this
  348. self.generate_module_init_func(modules[:-1], env, options, globalstate['init_module'])
  349. self.generate_module_cleanup_func(env, globalstate['cleanup_module'])
  350. if Options.embed:
  351. self.generate_main_method(env, globalstate['main_method'])
  352. self.generate_filename_table(globalstate['filename_table'])
  353. self.generate_declarations_for_modules(env, modules, globalstate)
  354. h_code.write('\n')
  355. for utilcode in env.utility_code_list[:]:
  356. globalstate.use_utility_code(utilcode)
  357. globalstate.finalize_main_c_code()
  358. f = open_new_file(result.c_file)
  359. try:
  360. rootwriter.copyto(f)
  361. finally:
  362. f.close()
  363. result.c_file_generated = 1
  364. if options.gdb_debug:
  365. self._serialize_lineno_map(env, rootwriter)
  366. if Options.annotate or options.annotate:
  367. self._generate_annotations(rootwriter, result, options)
  368. def _generate_annotations(self, rootwriter, result, options):
  369. self.annotate(rootwriter)
  370. coverage_xml_filename = Options.annotate_coverage_xml or options.annotate_coverage_xml
  371. if coverage_xml_filename and os.path.exists(coverage_xml_filename):
  372. try:
  373. import xml.etree.cElementTree as ET
  374. except ImportError:
  375. import xml.etree.ElementTree as ET
  376. coverage_xml = ET.parse(coverage_xml_filename).getroot()
  377. if hasattr(coverage_xml, 'iter'):
  378. iterator = coverage_xml.iter() # Python 2.7 & 3.2+
  379. else:
  380. iterator = coverage_xml.getiterator()
  381. for el in iterator:
  382. el.tail = None # save some memory
  383. else:
  384. coverage_xml = None
  385. rootwriter.save_annotation(result.main_source_file, result.c_file, coverage_xml=coverage_xml)
  386. # if we included files, additionally generate one annotation file for each
  387. if not self.scope.included_files:
  388. return
  389. search_include_file = self.scope.context.search_include_directories
  390. target_dir = os.path.abspath(os.path.dirname(result.c_file))
  391. for included_file in self.scope.included_files:
  392. target_file = os.path.abspath(os.path.join(target_dir, included_file))
  393. target_file_dir = os.path.dirname(target_file)
  394. if not target_file_dir.startswith(target_dir):
  395. # any other directories may not be writable => avoid trying
  396. continue
  397. source_file = search_include_file(included_file, "", self.pos, include=True)
  398. if not source_file:
  399. continue
  400. if target_file_dir != target_dir and not os.path.exists(target_file_dir):
  401. try:
  402. os.makedirs(target_file_dir)
  403. except OSError as e:
  404. import errno
  405. if e.errno != errno.EEXIST:
  406. raise
  407. rootwriter.save_annotation(source_file, target_file, coverage_xml=coverage_xml)
  408. def _serialize_lineno_map(self, env, ccodewriter):
  409. tb = env.context.gdb_debug_outputwriter
  410. markers = ccodewriter.buffer.allmarkers()
  411. d = defaultdict(list)
  412. for c_lineno, cython_lineno in enumerate(markers):
  413. if cython_lineno > 0:
  414. d[cython_lineno].append(c_lineno + 1)
  415. tb.start('LineNumberMapping')
  416. for cython_lineno, c_linenos in sorted(d.items()):
  417. tb.add_entry(
  418. 'LineNumber',
  419. c_linenos=' '.join(map(str, c_linenos)),
  420. cython_lineno=str(cython_lineno),
  421. )
  422. tb.end('LineNumberMapping')
  423. tb.serialize()
  424. def find_referenced_modules(self, env, module_list, modules_seen):
  425. if env not in modules_seen:
  426. modules_seen[env] = 1
  427. for imported_module in env.cimported_modules:
  428. self.find_referenced_modules(imported_module, module_list, modules_seen)
  429. module_list.append(env)
  430. def sort_types_by_inheritance(self, type_dict, type_order, getkey):
  431. # copy the types into a list moving each parent type before
  432. # its first child
  433. type_list = []
  434. for i, key in enumerate(type_order):
  435. new_entry = type_dict[key]
  436. # collect all base classes to check for children
  437. hierarchy = set()
  438. base = new_entry
  439. while base:
  440. base_type = base.type.base_type
  441. if not base_type:
  442. break
  443. base_key = getkey(base_type)
  444. hierarchy.add(base_key)
  445. base = type_dict.get(base_key)
  446. new_entry.base_keys = hierarchy
  447. # find the first (sub-)subclass and insert before that
  448. for j in range(i):
  449. entry = type_list[j]
  450. if key in entry.base_keys:
  451. type_list.insert(j, new_entry)
  452. break
  453. else:
  454. type_list.append(new_entry)
  455. return type_list
  456. def sort_type_hierarchy(self, module_list, env):
  457. # poor developer's OrderedDict
  458. vtab_dict, vtab_dict_order = {}, []
  459. vtabslot_dict, vtabslot_dict_order = {}, []
  460. for module in module_list:
  461. for entry in module.c_class_entries:
  462. if entry.used and not entry.in_cinclude:
  463. type = entry.type
  464. key = type.vtabstruct_cname
  465. if not key:
  466. continue
  467. if key in vtab_dict:
  468. # FIXME: this should *never* happen, but apparently it does
  469. # for Cython generated utility code
  470. from .UtilityCode import NonManglingModuleScope
  471. assert isinstance(entry.scope, NonManglingModuleScope), str(entry.scope)
  472. assert isinstance(vtab_dict[key].scope, NonManglingModuleScope), str(vtab_dict[key].scope)
  473. else:
  474. vtab_dict[key] = entry
  475. vtab_dict_order.append(key)
  476. all_defined_here = module is env
  477. for entry in module.type_entries:
  478. if entry.used and (all_defined_here or entry.defined_in_pxd):
  479. type = entry.type
  480. if type.is_extension_type and not entry.in_cinclude:
  481. type = entry.type
  482. key = type.objstruct_cname
  483. assert key not in vtabslot_dict, key
  484. vtabslot_dict[key] = entry
  485. vtabslot_dict_order.append(key)
  486. def vtabstruct_cname(entry_type):
  487. return entry_type.vtabstruct_cname
  488. vtab_list = self.sort_types_by_inheritance(
  489. vtab_dict, vtab_dict_order, vtabstruct_cname)
  490. def objstruct_cname(entry_type):
  491. return entry_type.objstruct_cname
  492. vtabslot_list = self.sort_types_by_inheritance(
  493. vtabslot_dict, vtabslot_dict_order, objstruct_cname)
  494. return (vtab_list, vtabslot_list)
  495. def sort_cdef_classes(self, env):
  496. key_func = operator.attrgetter('objstruct_cname')
  497. entry_dict, entry_order = {}, []
  498. for entry in env.c_class_entries:
  499. key = key_func(entry.type)
  500. assert key not in entry_dict, key
  501. entry_dict[key] = entry
  502. entry_order.append(key)
  503. env.c_class_entries[:] = self.sort_types_by_inheritance(
  504. entry_dict, entry_order, key_func)
  505. def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code):
  506. # TODO: Why are these separated out?
  507. for entry in vtabslot_list:
  508. self.generate_objstruct_predeclaration(entry.type, code)
  509. vtabslot_entries = set(vtabslot_list)
  510. ctuple_names = set()
  511. for module in modules:
  512. definition = module is env
  513. type_entries = []
  514. for entry in module.type_entries:
  515. if entry.type.is_ctuple and entry.used:
  516. if entry.name not in ctuple_names:
  517. ctuple_names.add(entry.name)
  518. type_entries.append(entry)
  519. elif definition or entry.defined_in_pxd:
  520. type_entries.append(entry)
  521. type_entries = [t for t in type_entries if t not in vtabslot_entries]
  522. self.generate_type_header_code(type_entries, code)
  523. for entry in vtabslot_list:
  524. self.generate_objstruct_definition(entry.type, code)
  525. self.generate_typeobj_predeclaration(entry, code)
  526. for entry in vtab_list:
  527. self.generate_typeobj_predeclaration(entry, code)
  528. self.generate_exttype_vtable_struct(entry, code)
  529. self.generate_exttype_vtabptr_declaration(entry, code)
  530. self.generate_exttype_final_methods_declaration(entry, code)
  531. def generate_declarations_for_modules(self, env, modules, globalstate):
  532. typecode = globalstate['type_declarations']
  533. typecode.putln("")
  534. typecode.putln("/*--- Type declarations ---*/")
  535. # This is to work around the fact that array.h isn't part of the C-API,
  536. # but we need to declare it earlier than utility code.
  537. if 'cpython.array' in [m.qualified_name for m in modules]:
  538. typecode.putln('#ifndef _ARRAYARRAY_H')
  539. typecode.putln('struct arrayobject;')
  540. typecode.putln('typedef struct arrayobject arrayobject;')
  541. typecode.putln('#endif')
  542. vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env)
  543. self.generate_type_definitions(
  544. env, modules, vtab_list, vtabslot_list, typecode)
  545. modulecode = globalstate['module_declarations']
  546. for module in modules:
  547. defined_here = module is env
  548. modulecode.putln("")
  549. modulecode.putln("/* Module declarations from '%s' */" % module.qualified_name)
  550. self.generate_c_class_declarations(module, modulecode, defined_here)
  551. self.generate_cvariable_declarations(module, modulecode, defined_here)
  552. self.generate_cfunction_declarations(module, modulecode, defined_here)
  553. def _put_setup_code(self, code, name):
  554. code.put(UtilityCode.load_as_string(name, "ModuleSetupCode.c")[1])
  555. def generate_module_preamble(self, env, options, cimported_modules, metadata, code):
  556. code.put_generated_by()
  557. if metadata:
  558. code.putln("/* BEGIN: Cython Metadata")
  559. code.putln(json.dumps(metadata, indent=4, sort_keys=True))
  560. code.putln("END: Cython Metadata */")
  561. code.putln("")
  562. code.putln("#ifndef PY_SSIZE_T_CLEAN")
  563. code.putln("#define PY_SSIZE_T_CLEAN")
  564. code.putln("#endif /* PY_SSIZE_T_CLEAN */")
  565. for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey):
  566. if inc.location == inc.INITIAL:
  567. inc.write(code)
  568. code.putln("#ifndef Py_PYTHON_H")
  569. code.putln(" #error Python headers needed to compile C extensions, "
  570. "please install development version of Python.")
  571. code.putln("#elif PY_VERSION_HEX < 0x02060000 || "
  572. "(0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)")
  573. code.putln(" #error Cython requires Python 2.6+ or Python 3.3+.")
  574. code.putln("#else")
  575. code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
  576. from .. import __version__
  577. code.putln('#define CYTHON_ABI "%s"' % __version__.replace('.', '_'))
  578. code.putln('#define CYTHON_HEX_VERSION %s' % build_hex_version(__version__))
  579. code.putln("#define CYTHON_FUTURE_DIVISION %d" % (
  580. Future.division in env.context.future_directives))
  581. self._put_setup_code(code, "CModulePreamble")
  582. if env.context.options.cplus:
  583. self._put_setup_code(code, "CppInitCode")
  584. else:
  585. self._put_setup_code(code, "CInitCode")
  586. self._put_setup_code(code, "PythonCompatibility")
  587. self._put_setup_code(code, "MathInitCode")
  588. # Using "(void)cname" to prevent "unused" warnings.
  589. if options.c_line_in_traceback:
  590. cinfo = "%s = %s; (void)%s; " % (Naming.clineno_cname, Naming.line_c_macro, Naming.clineno_cname)
  591. else:
  592. cinfo = ""
  593. code.putln("#define __PYX_MARK_ERR_POS(f_index, lineno) \\")
  594. code.putln(" { %s = %s[f_index]; (void)%s; %s = lineno; (void)%s; %s}" % (
  595. Naming.filename_cname, Naming.filetable_cname, Naming.filename_cname,
  596. Naming.lineno_cname, Naming.lineno_cname,
  597. cinfo
  598. ))
  599. code.putln("#define __PYX_ERR(f_index, lineno, Ln_error) \\")
  600. code.putln(" { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }")
  601. code.putln("")
  602. self.generate_extern_c_macro_definition(code)
  603. code.putln("")
  604. code.putln("#define %s" % Naming.h_guard_prefix + self.api_name(env))
  605. code.putln("#define %s" % Naming.api_guard_prefix + self.api_name(env))
  606. code.putln("/* Early includes */")
  607. self.generate_includes(env, cimported_modules, code, late=False)
  608. code.putln("")
  609. code.putln("#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)")
  610. code.putln("#define CYTHON_WITHOUT_ASSERTIONS")
  611. code.putln("#endif")
  612. code.putln("")
  613. if env.directives['ccomplex']:
  614. code.putln("")
  615. code.putln("#if !defined(CYTHON_CCOMPLEX)")
  616. code.putln("#define CYTHON_CCOMPLEX 1")
  617. code.putln("#endif")
  618. code.putln("")
  619. code.put(UtilityCode.load_as_string("UtilityFunctionPredeclarations", "ModuleSetupCode.c")[0])
  620. c_string_type = env.directives['c_string_type']
  621. c_string_encoding = env.directives['c_string_encoding']
  622. if c_string_type not in ('bytes', 'bytearray') and not c_string_encoding:
  623. error(self.pos, "a default encoding must be provided if c_string_type is not a byte type")
  624. code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII %s' % int(c_string_encoding == 'ascii'))
  625. code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 %s' %
  626. int(c_string_encoding.replace('-', '').lower() == 'utf8'))
  627. if c_string_encoding == 'default':
  628. code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 1')
  629. else:
  630. code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT '
  631. '(PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)')
  632. code.putln('#define __PYX_DEFAULT_STRING_ENCODING "%s"' % c_string_encoding)
  633. if c_string_type == 'bytearray':
  634. c_string_func_name = 'ByteArray'
  635. else:
  636. c_string_func_name = c_string_type.title()
  637. code.putln('#define __Pyx_PyObject_FromString __Pyx_Py%s_FromString' % c_string_func_name)
  638. code.putln('#define __Pyx_PyObject_FromStringAndSize __Pyx_Py%s_FromStringAndSize' % c_string_func_name)
  639. code.put(UtilityCode.load_as_string("TypeConversions", "TypeConversion.c")[0])
  640. # These utility functions are assumed to exist and used elsewhere.
  641. PyrexTypes.c_long_type.create_to_py_utility_code(env)
  642. PyrexTypes.c_long_type.create_from_py_utility_code(env)
  643. PyrexTypes.c_int_type.create_from_py_utility_code(env)
  644. code.put(Nodes.branch_prediction_macros)
  645. code.putln('static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }')
  646. code.putln('')
  647. code.putln('static PyObject *%s = NULL;' % env.module_cname)
  648. code.putln('static PyObject *%s;' % env.module_dict_cname)
  649. code.putln('static PyObject *%s;' % Naming.builtins_cname)
  650. code.putln('static PyObject *%s = NULL;' % Naming.cython_runtime_cname)
  651. code.putln('static PyObject *%s;' % Naming.empty_tuple)
  652. code.putln('static PyObject *%s;' % Naming.empty_bytes)
  653. code.putln('static PyObject *%s;' % Naming.empty_unicode)
  654. if Options.pre_import is not None:
  655. code.putln('static PyObject *%s;' % Naming.preimport_cname)
  656. code.putln('static int %s;' % Naming.lineno_cname)
  657. code.putln('static int %s = 0;' % Naming.clineno_cname)
  658. code.putln('static const char * %s= %s;' % (Naming.cfilenm_cname, Naming.file_c_macro))
  659. code.putln('static const char *%s;' % Naming.filename_cname)
  660. env.use_utility_code(UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c"))
  661. if has_np_pythran(env):
  662. env.use_utility_code(UtilityCode.load_cached("PythranConversion", "CppSupport.cpp"))
  663. def generate_extern_c_macro_definition(self, code):
  664. name = Naming.extern_c_macro
  665. code.putln("#ifndef %s" % name)
  666. code.putln(" #ifdef __cplusplus")
  667. code.putln(' #define %s extern "C"' % name)
  668. code.putln(" #else")
  669. code.putln(" #define %s extern" % name)
  670. code.putln(" #endif")
  671. code.putln("#endif")
  672. def generate_dl_import_macro(self, code):
  673. code.putln("#ifndef DL_IMPORT")
  674. code.putln(" #define DL_IMPORT(_T) _T")
  675. code.putln("#endif")
  676. def generate_includes(self, env, cimported_modules, code, early=True, late=True):
  677. includes = []
  678. for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey):
  679. if inc.location == inc.EARLY:
  680. if early:
  681. inc.write(code)
  682. elif inc.location == inc.LATE:
  683. if late:
  684. inc.write(code)
  685. if early:
  686. code.putln_openmp("#include <omp.h>")
  687. def generate_filename_table(self, code):
  688. from os.path import isabs, basename
  689. code.putln("")
  690. code.putln("static const char *%s[] = {" % Naming.filetable_cname)
  691. if code.globalstate.filename_list:
  692. for source_desc in code.globalstate.filename_list:
  693. file_path = source_desc.get_filenametable_entry()
  694. if Options.source_root:
  695. # If source root specified, dump description - it's source root relative filename
  696. file_path = source_desc.get_description()
  697. if isabs(file_path):
  698. file_path = basename(file_path) # never include absolute paths
  699. escaped_filename = file_path.replace("\\", "\\\\").replace('"', r'\"')
  700. code.putln('"%s",' % escaped_filename)
  701. else:
  702. # Some C compilers don't like an empty array
  703. code.putln("0")
  704. code.putln("};")
  705. def generate_type_predeclarations(self, env, code):
  706. pass
  707. def generate_type_header_code(self, type_entries, code):
  708. # Generate definitions of structs/unions/enums/typedefs/objstructs.
  709. #self.generate_gcc33_hack(env, code) # Is this still needed?
  710. # Forward declarations
  711. for entry in type_entries:
  712. if not entry.in_cinclude:
  713. #print "generate_type_header_code:", entry.name, repr(entry.type) ###
  714. type = entry.type
  715. if type.is_typedef: # Must test this first!
  716. pass
  717. elif type.is_struct_or_union or type.is_cpp_class:
  718. self.generate_struct_union_predeclaration(entry, code)
  719. elif type.is_ctuple and entry.used:
  720. self.generate_struct_union_predeclaration(entry.type.struct_entry, code)
  721. elif type.is_extension_type:
  722. self.generate_objstruct_predeclaration(type, code)
  723. # Actual declarations
  724. for entry in type_entries:
  725. if not entry.in_cinclude:
  726. #print "generate_type_header_code:", entry.name, repr(entry.type) ###
  727. type = entry.type
  728. if type.is_typedef: # Must test this first!
  729. self.generate_typedef(entry, code)
  730. elif type.is_enum:
  731. self.generate_enum_definition(entry, code)
  732. elif type.is_struct_or_union:
  733. self.generate_struct_union_definition(entry, code)
  734. elif type.is_ctuple and entry.used:
  735. self.generate_struct_union_definition(entry.type.struct_entry, code)
  736. elif type.is_cpp_class:
  737. self.generate_cpp_class_definition(entry, code)
  738. elif type.is_extension_type:
  739. self.generate_objstruct_definition(type, code)
  740. def generate_gcc33_hack(self, env, code):
  741. # Workaround for spurious warning generation in gcc 3.3
  742. code.putln("")
  743. for entry in env.c_class_entries:
  744. type = entry.type
  745. if not type.typedef_flag:
  746. name = type.objstruct_cname
  747. if name.startswith("__pyx_"):
  748. tail = name[6:]
  749. else:
  750. tail = name
  751. code.putln("typedef struct %s __pyx_gcc33_%s;" % (
  752. name, tail))
  753. def generate_typedef(self, entry, code):
  754. base_type = entry.type.typedef_base_type
  755. if base_type.is_numeric:
  756. try:
  757. writer = code.globalstate['numeric_typedefs']
  758. except KeyError:
  759. writer = code
  760. else:
  761. writer = code
  762. writer.mark_pos(entry.pos)
  763. writer.putln("typedef %s;" % base_type.declaration_code(entry.cname))
  764. def sue_predeclaration(self, type, kind, name):
  765. if type.typedef_flag:
  766. return "%s %s;\ntypedef %s %s %s;" % (
  767. kind, name,
  768. kind, name, name)
  769. else:
  770. return "%s %s;" % (kind, name)
  771. def generate_struct_union_predeclaration(self, entry, code):
  772. type = entry.type
  773. if type.is_cpp_class and type.templates:
  774. code.putln("template <typename %s>" % ", typename ".join(
  775. [T.empty_declaration_code() for T in type.templates]))
  776. code.putln(self.sue_predeclaration(type, type.kind, type.cname))
  777. def sue_header_footer(self, type, kind, name):
  778. header = "%s %s {" % (kind, name)
  779. footer = "};"
  780. return header, footer
  781. def generate_struct_union_definition(self, entry, code):
  782. code.mark_pos(entry.pos)
  783. type = entry.type
  784. scope = type.scope
  785. if scope:
  786. kind = type.kind
  787. packed = type.is_struct and type.packed
  788. if packed:
  789. kind = "%s %s" % (type.kind, "__Pyx_PACKED")
  790. code.globalstate.use_utility_code(packed_struct_utility_code)
  791. header, footer = \
  792. self.sue_header_footer(type, kind, type.cname)
  793. if packed:
  794. code.putln("#if defined(__SUNPRO_C)")
  795. code.putln(" #pragma pack(1)")
  796. code.putln("#elif !defined(__GNUC__)")
  797. code.putln(" #pragma pack(push, 1)")
  798. code.putln("#endif")
  799. code.putln(header)
  800. var_entries = scope.var_entries
  801. if not var_entries:
  802. error(entry.pos, "Empty struct or union definition not allowed outside a 'cdef extern from' block")
  803. for attr in var_entries:
  804. code.putln(
  805. "%s;" % attr.type.declaration_code(attr.cname))
  806. code.putln(footer)
  807. if packed:
  808. code.putln("#if defined(__SUNPRO_C)")
  809. code.putln(" #pragma pack()")
  810. code.putln("#elif !defined(__GNUC__)")
  811. code.putln(" #pragma pack(pop)")
  812. code.putln("#endif")
  813. def generate_cpp_class_definition(self, entry, code):
  814. code.mark_pos(entry.pos)
  815. type = entry.type
  816. scope = type.scope
  817. if scope:
  818. if type.templates:
  819. code.putln("template <class %s>" % ", class ".join(
  820. [T.empty_declaration_code() for T in type.templates]))
  821. # Just let everything be public.
  822. code.put("struct %s" % type.cname)
  823. if type.base_classes:
  824. base_class_decl = ", public ".join(
  825. [base_class.empty_declaration_code() for base_class in type.base_classes])
  826. code.put(" : public %s" % base_class_decl)
  827. code.putln(" {")
  828. py_attrs = [e for e in scope.entries.values()
  829. if e.type.is_pyobject and not e.is_inherited]
  830. has_virtual_methods = False
  831. constructor = None
  832. destructor = None
  833. for attr in scope.var_entries:
  834. if attr.type.is_cfunction:
  835. code.put("inline ")
  836. if attr.type.is_cfunction and attr.type.is_static_method:
  837. code.put("static ")
  838. elif attr.name == "<init>":
  839. constructor = attr
  840. elif attr.name == "<del>":
  841. destructor = attr
  842. elif attr.type.is_cfunction:
  843. code.put("virtual ")
  844. has_virtual_methods = True
  845. code.putln("%s;" % attr.type.declaration_code(attr.cname))
  846. is_implementing = 'init_module' in code.globalstate.parts
  847. if constructor or py_attrs:
  848. if constructor:
  849. arg_decls = []
  850. arg_names = []
  851. for arg in constructor.type.original_args[
  852. :len(constructor.type.args)-constructor.type.optional_arg_count]:
  853. arg_decls.append(arg.declaration_code())
  854. arg_names.append(arg.cname)
  855. if constructor.type.optional_arg_count:
  856. arg_decls.append(constructor.type.op_arg_struct.declaration_code(Naming.optional_args_cname))
  857. arg_names.append(Naming.optional_args_cname)
  858. if not arg_decls:
  859. arg_decls = ["void"]
  860. else:
  861. arg_decls = ["void"]
  862. arg_names = []
  863. if is_implementing:
  864. code.putln("%s(%s) {" % (type.cname, ", ".join(arg_decls)))
  865. if py_attrs:
  866. code.put_ensure_gil()
  867. for attr in py_attrs:
  868. code.put_init_var_to_py_none(attr, nanny=False);
  869. if constructor:
  870. code.putln("%s(%s);" % (constructor.cname, ", ".join(arg_names)))
  871. if py_attrs:
  872. code.put_release_ensured_gil()
  873. code.putln("}")
  874. else:
  875. code.putln("%s(%s);" % (type.cname, ", ".join(arg_decls)))
  876. if destructor or py_attrs or has_virtual_methods:
  877. if has_virtual_methods:
  878. code.put("virtual ")
  879. if is_implementing:
  880. code.putln("~%s() {" % type.cname)
  881. if py_attrs:
  882. code.put_ensure_gil()
  883. if destructor:
  884. code.putln("%s();" % destructor.cname)
  885. if py_attrs:
  886. for attr in py_attrs:
  887. code.put_var_xdecref(attr, nanny=False);
  888. code.put_release_ensured_gil()
  889. code.putln("}")
  890. else:
  891. code.putln("~%s();" % type.cname)
  892. if py_attrs:
  893. # Also need copy constructor and assignment operators.
  894. if is_implementing:
  895. code.putln("%s(const %s& __Pyx_other) {" % (type.cname, type.cname))
  896. code.put_ensure_gil()
  897. for attr in scope.var_entries:
  898. if not attr.type.is_cfunction:
  899. code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname))
  900. code.put_var_incref(attr, nanny=False)
  901. code.put_release_ensured_gil()
  902. code.putln("}")
  903. code.putln("%s& operator=(const %s& __Pyx_other) {" % (type.cname, type.cname))
  904. code.putln("if (this != &__Pyx_other) {")
  905. code.put_ensure_gil()
  906. for attr in scope.var_entries:
  907. if not attr.type.is_cfunction:
  908. code.put_var_xdecref(attr, nanny=False);
  909. code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname))
  910. code.put_var_incref(attr, nanny=False)
  911. code.put_release_ensured_gil()
  912. code.putln("}")
  913. code.putln("return *this;")
  914. code.putln("}")
  915. else:
  916. code.putln("%s(const %s& __Pyx_other);" % (type.cname, type.cname))
  917. code.putln("%s& operator=(const %s& __Pyx_other);" % (type.cname, type.cname))
  918. code.putln("};")
  919. def generate_enum_definition(self, entry, code):
  920. code.mark_pos(entry.pos)
  921. type = entry.type
  922. name = entry.cname or entry.name or ""
  923. header, footer = self.sue_header_footer(type, "enum", name)
  924. code.putln(header)
  925. enum_values = entry.enum_values
  926. if not enum_values:
  927. error(entry.pos, "Empty enum definition not allowed outside a 'cdef extern from' block")
  928. else:
  929. last_entry = enum_values[-1]
  930. # this does not really generate code, just builds the result value
  931. for value_entry in enum_values:
  932. if value_entry.value_node is not None:
  933. value_entry.value_node.generate_evaluation_code(code)
  934. for value_entry in enum_values:
  935. if value_entry.value_node is None:
  936. value_code = value_entry.cname
  937. else:
  938. value_code = ("%s = %s" % (
  939. value_entry.cname,
  940. value_entry.value_node.result()))
  941. if value_entry is not last_entry:
  942. value_code += ","
  943. code.putln(value_code)
  944. code.putln(footer)
  945. if entry.type.typedef_flag:
  946. # Not pre-declared.
  947. code.putln("typedef enum %s %s;" % (name, name))
  948. def generate_typeobj_predeclaration(self, entry, code):
  949. code.putln("")
  950. name = entry.type.typeobj_cname
  951. if name:
  952. if entry.visibility == 'extern' and not entry.in_cinclude:
  953. code.putln("%s %s %s;" % (
  954. Naming.extern_c_macro,
  955. PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"),
  956. name))
  957. elif entry.visibility == 'public':
  958. code.putln("%s %s %s;" % (
  959. Naming.extern_c_macro,
  960. PyrexTypes.public_decl("PyTypeObject", "DL_EXPORT"),
  961. name))
  962. # ??? Do we really need the rest of this? ???
  963. #else:
  964. # code.putln("static PyTypeObject %s;" % name)
  965. def generate_exttype_vtable_struct(self, entry, code):
  966. if not entry.used:
  967. return
  968. code.mark_pos(entry.pos)
  969. # Generate struct declaration for an extension type's vtable.
  970. type = entry.type
  971. scope = type.scope
  972. self.specialize_fused_types(scope)
  973. if type.vtabstruct_cname:
  974. code.putln("")
  975. code.putln("struct %s {" % type.vtabstruct_cname)
  976. if type.base_type and type.base_type.vtabstruct_cname:
  977. code.putln("struct %s %s;" % (
  978. type.base_type.vtabstruct_cname,
  979. Naming.obj_base_cname))
  980. for method_entry in scope.cfunc_entries:
  981. if not method_entry.is_inherited:
  982. code.putln("%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.cname))
  983. code.putln("};")
  984. def generate_exttype_vtabptr_declaration(self, entry, code):
  985. if not entry.used:
  986. return
  987. code.mark_pos(entry.pos)
  988. # Generate declaration of pointer to an extension type's vtable.
  989. type = entry.type
  990. if type.vtabptr_cname:
  991. code.putln("static struct %s *%s;" % (
  992. type.vtabstruct_cname,
  993. type.vtabptr_cname))
  994. def generate_exttype_final_methods_declaration(self, entry, code):
  995. if not entry.used:
  996. return
  997. code.mark_pos(entry.pos)
  998. # Generate final methods prototypes
  999. type = entry.type
  1000. for method_entry in entry.type.scope.cfunc_entries:
  1001. if not method_entry.is_inherited and method_entry.final_func_cname:
  1002. declaration = method_entry.type.declaration_code(
  1003. method_entry.final_func_cname)
  1004. modifiers = code.build_function_modifiers(method_entry.func_modifiers)
  1005. code.putln("static %s%s;" % (modifiers, declaration))
  1006. def generate_objstruct_predeclaration(self, type, code):
  1007. if not type.scope:
  1008. return
  1009. code.putln(self.sue_predeclaration(type, "struct", type.objstruct_cname))
  1010. def generate_objstruct_definition(self, type, code):
  1011. code.mark_pos(type.pos)
  1012. # Generate object struct definition for an
  1013. # extension type.
  1014. if not type.scope:
  1015. return # Forward declared but never defined
  1016. header, footer = \
  1017. self.sue_header_footer(type, "struct", type.objstruct_cname)
  1018. code.putln(header)
  1019. base_type = type.base_type
  1020. if base_type:
  1021. basestruct_cname = base_type.objstruct_cname
  1022. if basestruct_cname == "PyTypeObject":
  1023. # User-defined subclasses of type are heap allocated.
  1024. basestruct_cname = "PyHeapTypeObject"
  1025. code.putln(
  1026. "%s%s %s;" % (
  1027. ("struct ", "")[base_type.typedef_flag],
  1028. basestruct_cname,
  1029. Naming.obj_base_cname))
  1030. else:
  1031. code.putln(
  1032. "PyObject_HEAD")
  1033. if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname):
  1034. code.putln(
  1035. "struct %s *%s;" % (
  1036. type.vtabstruct_cname,
  1037. type.vtabslot_cname))
  1038. for attr in type.scope.var_entries:
  1039. if attr.is_declared_generic:
  1040. attr_type = py_object_type
  1041. else:
  1042. attr_type = attr.type
  1043. code.putln(
  1044. "%s;" % attr_type.declaration_code(attr.cname))
  1045. code.putln(footer)
  1046. if type.objtypedef_cname is not None:
  1047. # Only for exposing public typedef name.
  1048. code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname))
  1049. def generate_c_class_declarations(self, env, code, definition):
  1050. for entry in env.c_class_entries:
  1051. if definition or entry.defined_in_pxd:
  1052. code.putln("static PyTypeObject *%s = 0;" % (
  1053. entry.type.typeptr_cname))
  1054. def generate_cvariable_declarations(self, env, code, definition):
  1055. if env.is_cython_builtin:
  1056. return
  1057. for entry in env.var_entries:
  1058. if (entry.in_cinclude or entry.in_closure or
  1059. (entry.visibility == 'private' and not (entry.defined_in_pxd or entry.used))):
  1060. continue
  1061. storage_class = None
  1062. dll_linkage = None
  1063. init = None
  1064. if entry.visibility == 'extern':
  1065. storage_class = Naming.extern_c_macro
  1066. dll_linkage = "DL_IMPORT"
  1067. elif entry.visibility == 'public':
  1068. storage_class = Naming.extern_c_macro
  1069. if definition:
  1070. dll_linkage = "DL_EXPORT"
  1071. else:
  1072. dll_linkage = "DL_IMPORT"
  1073. elif entry.visibility == 'private':
  1074. storage_class = "static"
  1075. dll_linkage = None
  1076. if entry.init is not None:
  1077. init = entry.type.literal_code(entry.init)
  1078. type = entry.type
  1079. cname = entry.cname
  1080. if entry.defined_in_pxd and not definition:
  1081. storage_class = "static"
  1082. dll_linkage = None
  1083. type = CPtrType(type)
  1084. cname = env.mangle(Naming.varptr_prefix, entry.name)
  1085. init = 0
  1086. if storage_class:
  1087. code.put("%s " % storage_class)
  1088. code.put(type.declaration_code(
  1089. cname, dll_linkage=dll_linkage))
  1090. if init is not None:
  1091. code.put_safe(" = %s" % init)
  1092. code.putln(";")
  1093. if entry.cname != cname:
  1094. code.putln("#define %s (*%s)" % (entry.cname, cname))
  1095. def generate_cfunction_declarations(self, env, code, definition):
  1096. for entry in env.cfunc_entries:
  1097. if entry.used or (entry.visibility == 'public' or entry.api):
  1098. generate_cfunction_declaration(entry, env, code, definition)
  1099. def generate_variable_definitions(self, env, code):
  1100. for entry in env.var_entries:
  1101. if not entry.in_cinclude and entry.visibility == "public":
  1102. code.put(entry.type.declaration_code(entry.cname))
  1103. if entry.init is not None:
  1104. init = entry.type.literal_code(entry.init)
  1105. code.put_safe(" = %s" % init)
  1106. code.putln(";")
  1107. def generate_typeobj_definitions(self, env, code):
  1108. full_module_name = env.qualified_name
  1109. for entry in env.c_class_entries:
  1110. #print "generate_typeobj_definitions:", entry.name
  1111. #print "...visibility =", entry.visibility
  1112. if entry.visibility != 'extern':
  1113. type = entry.type
  1114. scope = type.scope
  1115. if scope: # could be None if there was an error
  1116. if not scope.directives['c_api_binop_methods']:
  1117. error(self.pos,
  1118. "The 'c_api_binop_methods' directive is only supported for forward compatibility"
  1119. " and must be True.")
  1120. self.generate_exttype_vtable(scope, code)
  1121. self.generate_new_function(scope, code, entry)
  1122. self.generate_dealloc_function(scope, code)
  1123. if scope.needs_gc():
  1124. self.generate_traverse_function(scope, code, entry)
  1125. if scope.needs_tp_clear():
  1126. self.generate_clear_function(scope, code, entry)
  1127. if scope.defines_any_special(["__getitem__"]):
  1128. self.generate_getitem_int_function(scope, code)
  1129. if scope.defines_any_special(["__setitem__", "__delitem__"]):
  1130. self.generate_ass_subscript_function(scope, code)
  1131. if scope.defines_any_special(["__getslice__", "__setslice__", "__delslice__"]):
  1132. warning(self.pos,
  1133. "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, "
  1134. "use __getitem__, __setitem__, and __delitem__ instead", 1)
  1135. code.putln("#if PY_MAJOR_VERSION >= 3")
  1136. code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.")
  1137. code.putln("#endif")
  1138. if scope.defines_any_special(["__setslice__", "__delslice__"]):
  1139. self.generate_ass_slice_function(scope, code)
  1140. if scope.defines_any_special(["__getattr__", "__getattribute__"]):
  1141. self.generate_getattro_function(scope, code)
  1142. if scope.defines_any_special(["__setattr__", "__delattr__"]):
  1143. self.generate_setattro_function(scope, code)
  1144. if scope.defines_any_special(["__get__"]):
  1145. self.generate_descr_get_function(scope, code)
  1146. if scope.defines_any_special(["__set__", "__delete__"]):
  1147. self.generate_descr_set_function(scope, code)
  1148. if not scope.is_closure_class_scope and scope.defines_any(["__dict__"]):
  1149. self.generate_dict_getter_function(scope, code)
  1150. if scope.defines_any_special(TypeSlots.richcmp_special_methods):
  1151. self.generate_richcmp_function(scope, code)
  1152. self.generate_property_accessors(scope, code)
  1153. self.generate_method_table(scope, code)
  1154. self.generate_getset_table(scope, code)
  1155. self.generate_typeobj_definition(full_module_name, entry, code)
  1156. def generate_exttype_vtable(self, scope, code):
  1157. # Generate the definition of an extension type's vtable.
  1158. type = scope.parent_type
  1159. if type.vtable_cname:
  1160. code.putln("static struct %s %s;" % (
  1161. type.vtabstruct_cname,
  1162. type.vtable_cname))
  1163. def generate_self_cast(self, scope, code):
  1164. type = scope.parent_type
  1165. code.putln(
  1166. "%s = (%s)o;" % (
  1167. type.declaration_code("p"),
  1168. type.empty_declaration_code()))
  1169. def generate_new_function(self, scope, code, cclass_entry):
  1170. tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
  1171. slot_func = scope.mangle_internal("tp_new")
  1172. type = scope.parent_type
  1173. base_type = type.base_type
  1174. have_entries, (py_attrs, py_buffers, memoryview_slices) = \
  1175. scope.get_refcounted_entries()
  1176. is_final_type = scope.parent_type.is_final_type
  1177. if scope.is_internal:
  1178. # internal classes (should) never need None inits, normal zeroing will do
  1179. py_attrs = []
  1180. cpp_class_attrs = [entry for entry in scope.var_entries
  1181. if entry.type.is_cpp_class]
  1182. new_func_entry = scope.lookup_here("__new__")
  1183. if base_type or (new_func_entry and new_func_entry.is_special
  1184. and not new_func_entry.trivial_signature):
  1185. unused_marker = ''
  1186. else:
  1187. unused_marker = 'CYTHON_UNUSED '
  1188. if base_type:
  1189. freelist_size = 0 # not currently supported
  1190. else:
  1191. freelist_size = scope.directives.get('freelist', 0)
  1192. freelist_name = scope.mangle_internal(Naming.freelist_name)
  1193. freecount_name = scope.mangle_internal(Naming.freecount_name)
  1194. decls = code.globalstate['decls']
  1195. decls.putln("static PyObject *%s(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/" %
  1196. slot_func)
  1197. code.putln("")
  1198. if freelist_size:
  1199. code.putln("static %s[%d];" % (
  1200. scope.parent_type.declaration_code(freelist_name),
  1201. freelist_size))
  1202. code.putln("static int %s = 0;" % freecount_name)
  1203. code.putln("")
  1204. code.putln(
  1205. "static PyObject *%s(PyTypeObject *t, %sPyObject *a, %sPyObject *k) {" % (
  1206. slot_func, unused_marker, unused_marker))
  1207. need_self_cast = (type.vtabslot_cname or
  1208. (py_buffers or memoryview_slices or py_attrs) or
  1209. cpp_class_attrs)
  1210. if need_self_cast:
  1211. code.putln("%s;" % scope.parent_type.declaration_code("p"))
  1212. if base_type:
  1213. tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
  1214. if tp_new is None:
  1215. tp_new = "%s->tp_new" % base_type.typeptr_cname
  1216. code.putln("PyObject *o = %s(t, a, k);" % tp_new)
  1217. else:
  1218. code.putln("PyObject *o;")
  1219. if freelist_size:
  1220. code.globalstate.use_utility_code(
  1221. UtilityCode.load_cached("IncludeStringH", "StringTools.c"))
  1222. if is_final_type:
  1223. type_safety_check = ''
  1224. else:
  1225. type_safety_check = ' & (int)((t->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0)'
  1226. obj_struct = type.declaration_code("", deref=True)
  1227. code.putln(
  1228. "if (CYTHON_COMPILING_IN_CPYTHON & likely((int)(%s > 0) & (int)(t->tp_basicsize == sizeof(%s))%s)) {" % (
  1229. freecount_name, obj_struct, type_safety_check))
  1230. code.putln("o = (PyObject*)%s[--%s];" % (
  1231. freelist_name, freecount_name))
  1232. code.putln("memset(o, 0, sizeof(%s));" % obj_struct)
  1233. code.putln("(void) PyObject_INIT(o, t);")
  1234. if scope.needs_gc():
  1235. code.putln("PyObject_GC_Track(o);")
  1236. code.putln("} else {")
  1237. if not is_final_type:
  1238. code.putln("if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) {")
  1239. code.putln("o = (*t->tp_alloc)(t, 0);")
  1240. if not is_final_type:
  1241. code.putln("} else {")
  1242. code.putln("o = (PyObject *) PyBaseObject_Type.tp_new(t, %s, 0);" % Naming.empty_tuple)
  1243. code.putln("}")
  1244. code.putln("if (unlikely(!o)) return 0;")
  1245. if freelist_size and not base_type:
  1246. code.putln('}')
  1247. if need_self_cast:
  1248. code.putln("p = %s;" % type.cast_code("o"))
  1249. #if need_self_cast:
  1250. # self.generate_self_cast(scope, code)
  1251. # from this point on, ensure DECREF(o) on failure
  1252. needs_error_cleanup = False
  1253. if type.vtabslot_cname:
  1254. vtab_base_type = type
  1255. while vtab_base_type.base_type and vtab_base_type.base_type.vtabstruct_cname:
  1256. vtab_base_type = vtab_base_type.base_type
  1257. if vtab_base_type is not type:
  1258. struct_type_cast = "(struct %s*)" % vtab_base_type.vtabstruct_cname
  1259. else:
  1260. struct_type_cast = ""
  1261. code.putln("p->%s = %s%s;" % (
  1262. type.vtabslot_cname,
  1263. struct_type_cast, type.vtabptr_cname))
  1264. for entry in cpp_class_attrs:
  1265. code.putln("new((void*)&(p->%s)) %s();" % (
  1266. entry.cname, entry.type.empty_declaration_code()))
  1267. for entry in py_attrs:
  1268. if entry.name == "__dict__":
  1269. needs_error_cleanup = True
  1270. code.put("p->%s = PyDict_New(); if (unlikely(!p->%s)) goto bad;" % (
  1271. entry.cname, entry.cname))
  1272. else:
  1273. code.put_init_var_to_py_none(entry, "p->%s", nanny=False)
  1274. for entry in memoryview_slices:
  1275. code.putln("p->%s.data = NULL;" % entry.cname)
  1276. code.putln("p->%s.memview = NULL;" % entry.cname)
  1277. for entry in py_buffers:
  1278. code.putln("p->%s.obj = NULL;" % entry.cname)
  1279. if cclass_entry.cname == '__pyx_memoryviewslice':
  1280. code.putln("p->from_slice.memview = NULL;")
  1281. if new_func_entry and new_func_entry.is_special:
  1282. if new_func_entry.trivial_signature:
  1283. cinit_args = "o, %s, NULL" % Naming.empty_tuple
  1284. else:
  1285. cinit_args = "o, a, k"
  1286. needs_error_cleanup = True
  1287. code.putln("if (unlikely(%s(%s) < 0)) goto bad;" % (
  1288. new_func_entry.func_cname, cinit_args))
  1289. code.putln(
  1290. "return o;")
  1291. if needs_error_cleanup:
  1292. code.putln("bad:")
  1293. code.put_decref_clear("o", py_object_type, nanny=False)
  1294. code.putln("return NULL;")
  1295. code.putln(
  1296. "}")
  1297. def generate_dealloc_function(self, scope, code):
  1298. tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
  1299. slot_func = scope.mangle_internal("tp_dealloc")
  1300. base_type = scope.parent_type.base_type
  1301. if tp_slot.slot_code(scope) != slot_func:
  1302. return # never used
  1303. slot_func_cname = scope.mangle_internal("tp_dealloc")
  1304. code.putln("")
  1305. code.putln(
  1306. "static void %s(PyObject *o) {" % slot_func_cname)
  1307. is_final_type = scope.parent_type.is_final_type
  1308. needs_gc = scope.needs_gc()
  1309. weakref_slot = scope.lookup_here("__weakref__") if not scope.is_closure_class_scope else None
  1310. if weakref_slot not in scope.var_entries:
  1311. weakref_slot = None
  1312. dict_slot = scope.lookup_here("__dict__") if not scope.is_closure_class_scope else None
  1313. if dict_slot not in scope.var_entries:
  1314. dict_slot = None
  1315. _, (py_attrs, _, memoryview_slices) = scope.get_refcounted_entries()
  1316. cpp_class_attrs = [entry for entry in scope.var_entries
  1317. if entry.type.is_cpp_class]
  1318. if py_attrs or cpp_class_attrs or memoryview_slices or weakref_slot or dict_slot:
  1319. self.generate_self_cast(scope, code)
  1320. if not is_final_type:
  1321. # in Py3.4+, call tp_finalize() as early as possible
  1322. code.putln("#if CYTHON_USE_TP_FINALIZE")
  1323. if needs_gc:
  1324. finalised_check = '!__Pyx_PyObject_GC_IsFinalized(o)'
  1325. else:
  1326. finalised_check = (
  1327. '(!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))')
  1328. code.putln(
  1329. "if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)"
  1330. " && Py_TYPE(o)->tp_finalize) && %s) {" % finalised_check)
  1331. # if instance was resurrected by finaliser, return
  1332. code.putln("if (PyObject_CallFinalizerFromDealloc(o)) return;")
  1333. code.putln("}")
  1334. code.putln("#endif")
  1335. if needs_gc:
  1336. # We must mark this object as (gc) untracked while tearing
  1337. # it down, lest the garbage collection is invoked while
  1338. # running this destructor.
  1339. code.putln("PyObject_GC_UnTrack(o);")
  1340. # call the user's __dealloc__
  1341. self.generate_usr_dealloc_call(scope, code)
  1342. if weakref_slot:
  1343. code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);")
  1344. if dict_slot:
  1345. code.putln("if (p->__dict__) PyDict_Clear(p->__dict__);")
  1346. for entry in cpp_class_attrs:
  1347. code.putln("__Pyx_call_destructor(p->%s);" % entry.cname)
  1348. for entry in py_attrs:
  1349. code.put_xdecref_clear("p->%s" % entry.cname, entry.type, nanny=False,
  1350. clear_before_decref=True)
  1351. for entry in memoryview_slices:
  1352. code.put_xdecref_memoryviewslice("p->%s" % entry.cname,
  1353. have_gil=True)
  1354. if base_type:
  1355. base_cname = base_type.typeptr_cname
  1356. if needs_gc:
  1357. # The base class deallocator probably expects this to be tracked,
  1358. # so undo the untracking above.
  1359. if base_type.scope and base_type.scope.needs_gc():
  1360. code.putln("PyObject_GC_Track(o);")
  1361. else:
  1362. # Need to check type pointer, see comment on dealloc call below.
  1363. code.putln("if (%sPyType_IS_GC(%s)) PyObject_GC_Track(o);" % (
  1364. "" if base_type.is_builtin_type else "likely(%s) && " % base_cname,
  1365. base_cname))
  1366. tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
  1367. if tp_dealloc is not None:
  1368. code.putln("%s(o);" % tp_dealloc)
  1369. elif base_type.is_builtin_type:
  1370. code.putln("%s->tp_dealloc(o);" % base_cname)
  1371. else:
  1372. # This is an externally defined type. Calling through the
  1373. # cimported base type pointer directly interacts badly with
  1374. # the module cleanup, which may already have cleared it.
  1375. # In that case, fall back to traversing the type hierarchy.
  1376. code.putln("if (likely(%s)) %s->tp_dealloc(o); "
  1377. "else __Pyx_call_next_tp_dealloc(o, %s);" % (
  1378. base_cname, base_cname, slot_func_cname))
  1379. code.globalstate.use_utility_code(
  1380. UtilityCode.load_cached("CallNextTpDealloc", "ExtensionTypes.c"))
  1381. else:
  1382. freelist_size = scope.directives.get('freelist', 0)
  1383. if freelist_size:
  1384. freelist_name = scope.mangle_internal(Naming.freelist_name)
  1385. freecount_name = scope.mangle_internal(Naming.freecount_name)
  1386. if is_final_type:
  1387. type_safety_check = ''
  1388. else:
  1389. type_safety_check = (
  1390. ' & (int)((Py_TYPE(o)->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0)')
  1391. type = scope.parent_type
  1392. code.putln(
  1393. "if (CYTHON_COMPILING_IN_CPYTHON & ((int)(%s < %d) & (int)(Py_TYPE(o)->tp_basicsize == sizeof(%s))%s)) {" % (
  1394. freecount_name,
  1395. freelist_size,
  1396. type.declaration_code("", deref=True),
  1397. type_safety_check))
  1398. code.putln("%s[%s++] = %s;" % (
  1399. freelist_name, freecount_name, type.cast_code("o")))
  1400. code.putln("} else {")
  1401. code.putln("(*Py_TYPE(o)->tp_free)(o);")
  1402. if freelist_size:
  1403. code.putln("}")
  1404. code.putln(
  1405. "}")
  1406. def generate_usr_dealloc_call(self, scope, code):
  1407. entry = scope.lookup_here("__dealloc__")
  1408. if not entry:
  1409. return
  1410. code.putln("{")
  1411. code.putln("PyObject *etype, *eval, *etb;")
  1412. code.putln("PyErr_Fetch(&etype, &eval, &etb);")
  1413. # increase the refcount while we are calling into user code
  1414. # to prevent recursive deallocation
  1415. code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1);")
  1416. code.putln("%s(o);" % entry.func_cname)
  1417. code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1);")
  1418. code.putln("PyErr_Restore(etype, eval, etb);")
  1419. code.putln("}")
  1420. def generate_traverse_function(self, scope, code, cclass_entry):
  1421. tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
  1422. slot_func = scope.mangle_internal("tp_traverse")
  1423. base_type = scope.parent_type.base_type
  1424. if tp_slot.slot_code(scope) != slot_func:
  1425. return # never used
  1426. code.putln("")
  1427. code.putln(
  1428. "static int %s(PyObject *o, visitproc v, void *a) {" % slot_func)
  1429. have_entries, (py_attrs, py_buffers, memoryview_slices) = (
  1430. scope.get_refcounted_entries(include_gc_simple=False))
  1431. if base_type or py_attrs:
  1432. code.putln("int e;")
  1433. if py_attrs or py_buffers:
  1434. self.generate_self_cast(scope, code)
  1435. if base_type:
  1436. # want to call it explicitly if possible so inlining can be performed
  1437. static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
  1438. if static_call:
  1439. code.putln("e = %s(o, v, a); if (e) return e;" % static_call)
  1440. elif base_type.is_builtin_type:
  1441. base_cname = base_type.typeptr_cname
  1442. code.putln("if (!%s->tp_traverse); else { e = %s->tp_traverse(o,v,a); if (e) return e; }" % (
  1443. base_cname, base_cname))
  1444. else:
  1445. # This is an externally defined type. Calling through the
  1446. # cimported base type pointer directly interacts badly with
  1447. # the module cleanup, which may already have cleared it.
  1448. # In that case, fall back to traversing the type hierarchy.
  1449. base_cname = base_type.typeptr_cname
  1450. code.putln(
  1451. "e = ((likely(%s)) ? ((%s->tp_traverse) ? %s->tp_traverse(o, v, a) : 0) : "
  1452. "__Pyx_call_next_tp_traverse(o, v, a, %s)); if (e) return e;" % (
  1453. base_cname, base_cname, base_cname, slot_func))
  1454. code.globalstate.use_utility_code(
  1455. UtilityCode.load_cached("CallNextTpTraverse", "ExtensionTypes.c"))
  1456. for entry in py_attrs:
  1457. var_code = "p->%s" % entry.cname
  1458. var_as_pyobject = PyrexTypes.typecast(py_object_type, entry.type, var_code)
  1459. code.putln("if (%s) {" % var_code)
  1460. code.putln("e = (*v)(%s, a); if (e) return e;" % var_as_pyobject)
  1461. code.putln("}")
  1462. # Traverse buffer exporting objects.
  1463. # Note: not traversing memoryview attributes of memoryview slices!
  1464. # When triggered by the GC, it would cause multiple visits (gc_refs
  1465. # subtractions which is not matched by its reference count!)
  1466. for entry in py_buffers:
  1467. cname = entry.cname + ".obj"
  1468. code.putln("if (p->%s) {" % cname)
  1469. code.putln("e = (*v)(p->%s, a); if (e) return e;" % cname)
  1470. code.putln("}")
  1471. code.putln("return 0;")
  1472. code.putln("}")
  1473. def generate_clear_function(self, scope, code, cclass_entry):
  1474. tp_slot = TypeSlots.get_slot_by_name("tp_clear")
  1475. slot_func = scope.mangle_internal("tp_clear")
  1476. base_type = scope.parent_type.base_type
  1477. if tp_slot.slot_code(scope) != slot_func:
  1478. return # never used
  1479. have_entries, (py_attrs, py_buffers, memoryview_slices) = (
  1480. scope.get_refcounted_entries(include_gc_simple=False))
  1481. if py_attrs or py_buffers or base_type:
  1482. unused = ''
  1483. else:
  1484. unused = 'CYTHON_UNUSED '
  1485. code.putln("")
  1486. code.putln("static int %s(%sPyObject *o) {" % (slot_func, unused))
  1487. if py_attrs and Options.clear_to_none:
  1488. code.putln("PyObject* tmp;")
  1489. if py_attrs or py_buffers:
  1490. self.generate_self_cast(scope, code)
  1491. if base_type:
  1492. # want to call it explicitly if possible so inlining can be performed
  1493. static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
  1494. if static_call:
  1495. code.putln("%s(o);" % static_call)
  1496. elif base_type.is_builtin_type:
  1497. base_cname = base_type.typeptr_cname
  1498. code.putln("if (!%s->tp_clear); else %s->tp_clear(o);" % (
  1499. base_cname, base_cname))
  1500. else:
  1501. # This is an externally defined type. Calling through the
  1502. # cimported base type pointer directly interacts badly with
  1503. # the module cleanup, which may already have cleared it.
  1504. # In that case, fall back to traversing the type hierarchy.
  1505. base_cname = base_type.typeptr_cname
  1506. code.putln(
  1507. "if (likely(%s)) { if (%s->tp_clear) %s->tp_clear(o); } else __Pyx_call_next_tp_clear(o, %s);" % (
  1508. base_cname, base_cname, base_cname, slot_func))
  1509. code.globalstate.use_utility_code(
  1510. UtilityCode.load_cached("CallNextTpClear", "ExtensionTypes.c"))
  1511. if Options.clear_to_none:
  1512. for entry in py_attrs:
  1513. name = "p->%s" % entry.cname
  1514. code.putln("tmp = ((PyObject*)%s);" % name)
  1515. if entry.is_declared_generic:
  1516. code.put_init_to_py_none(name, py_object_type, nanny=False)
  1517. else:
  1518. code.put_init_to_py_none(name, entry.type, nanny=False)
  1519. code.putln("Py_XDECREF(tmp);")
  1520. else:
  1521. for entry in py_attrs:
  1522. code.putln("Py_CLEAR(p->%s);" % entry.cname)
  1523. for entry in py_buffers:
  1524. # Note: shouldn't this call __Pyx_ReleaseBuffer ??
  1525. code.putln("Py_CLEAR(p->%s.obj);" % entry.cname)
  1526. if cclass_entry.cname == '__pyx_memoryviewslice':
  1527. code.putln("__PYX_XDEC_MEMVIEW(&p->from_slice, 1);")
  1528. code.putln("return 0;")
  1529. code.putln("}")
  1530. def generate_getitem_int_function(self, scope, code):
  1531. # This function is put into the sq_item slot when
  1532. # a __getitem__ method is present. It converts its
  1533. # argument to a Python integer and calls mp_subscript.
  1534. code.putln(
  1535. "static PyObject *%s(PyObject *o, Py_ssize_t i) {" % (
  1536. scope.mangle_internal("sq_item")))
  1537. code.putln(
  1538. "PyObject *r;")
  1539. code.putln(
  1540. "PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;")
  1541. code.putln(
  1542. "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
  1543. code.putln(
  1544. "Py_DECREF(x);")
  1545. code.putln(
  1546. "return r;")
  1547. code.putln(
  1548. "}")
  1549. def generate_ass_subscript_function(self, scope, code):
  1550. # Setting and deleting an item are both done through
  1551. # the ass_subscript method, so we dispatch to user's __setitem__
  1552. # or __delitem__, or raise an exception.
  1553. base_type = scope.parent_type.base_type
  1554. set_entry = scope.lookup_here("__setitem__")
  1555. del_entry = scope.lookup_here("__delitem__")
  1556. code.putln("")
  1557. code.putln(
  1558. "static int %s(PyObject *o, PyObject *i, PyObject *v) {" % (
  1559. scope.mangle_internal("mp_ass_subscript")))
  1560. code.putln(
  1561. "if (v) {")
  1562. if set_entry:
  1563. code.putln("return %s(o, i, v);" % set_entry.func_cname)
  1564. else:
  1565. self.generate_guarded_basetype_call(
  1566. base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
  1567. code.putln(
  1568. "PyErr_Format(PyExc_NotImplementedError,")
  1569. code.putln(
  1570. ' "Subscript assignment not supported by %.200s", Py_TYPE(o)->tp_name);')
  1571. code.putln(
  1572. "return -1;")
  1573. code.putln(
  1574. "}")
  1575. code.putln(
  1576. "else {")
  1577. if del_entry:
  1578. code.putln(
  1579. "return %s(o, i);" % (
  1580. del_entry.func_cname))
  1581. else:
  1582. self.generate_guarded_basetype_call(
  1583. base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
  1584. code.putln(
  1585. "PyErr_Format(PyExc_NotImplementedError,")
  1586. code.putln(
  1587. ' "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name);')
  1588. code.putln(
  1589. "return -1;")
  1590. code.putln(
  1591. "}")
  1592. code.putln(
  1593. "}")
  1594. def generate_guarded_basetype_call(
  1595. self, base_type, substructure, slot, args, code):
  1596. if base_type:
  1597. base_tpname = base_type.typeptr_cname
  1598. if substructure:
  1599. code.putln(
  1600. "if (%s->%s && %s->%s->%s)" % (
  1601. base_tpname, substructure, base_tpname, substructure, slot))
  1602. code.putln(
  1603. " return %s->%s->%s(%s);" % (
  1604. base_tpname, substructure, slot, args))
  1605. else:
  1606. code.putln(
  1607. "if (%s->%s)" % (
  1608. base_tpname, slot))
  1609. code.putln(
  1610. " return %s->%s(%s);" % (
  1611. base_tpname, slot, args))
  1612. def generate_ass_slice_function(self, scope, code):
  1613. # Setting and deleting a slice are both done through
  1614. # the ass_slice method, so we dispatch to user's __setslice__
  1615. # or __delslice__, or raise an exception.
  1616. base_type = scope.parent_type.base_type
  1617. set_entry = scope.lookup_here("__setslice__")
  1618. del_entry = scope.lookup_here("__delslice__")
  1619. code.putln("")
  1620. code.putln(
  1621. "static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" % (
  1622. scope.mangle_internal("sq_ass_slice")))
  1623. code.putln(
  1624. "if (v) {")
  1625. if set_entry:
  1626. code.putln(
  1627. "return %s(o, i, j, v);" % (
  1628. set_entry.func_cname))
  1629. else:
  1630. self.generate_guarded_basetype_call(
  1631. base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
  1632. code.putln(
  1633. "PyErr_Format(PyExc_NotImplementedError,")
  1634. code.putln(
  1635. ' "2-element slice assignment not supported by %.200s", Py_TYPE(o)->tp_name);')
  1636. code.putln(
  1637. "return -1;")
  1638. code.putln(
  1639. "}")
  1640. code.putln(
  1641. "else {")
  1642. if del_entry:
  1643. code.putln(
  1644. "return %s(o, i, j);" % (
  1645. del_entry.func_cname))
  1646. else:
  1647. self.generate_guarded_basetype_call(
  1648. base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
  1649. code.putln(
  1650. "PyErr_Format(PyExc_NotImplementedError,")
  1651. code.putln(
  1652. ' "2-element slice deletion not supported by %.200s", Py_TYPE(o)->tp_name);')
  1653. code.putln(
  1654. "return -1;")
  1655. code.putln(
  1656. "}")
  1657. code.putln(
  1658. "}")
  1659. def generate_richcmp_function(self, scope, code):
  1660. if scope.lookup_here("__richcmp__"):
  1661. # user implemented, nothing to do
  1662. return
  1663. # otherwise, we have to generate it from the Python special methods
  1664. richcmp_cfunc = scope.mangle_internal("tp_richcompare")
  1665. code.putln("")
  1666. code.putln("static PyObject *%s(PyObject *o1, PyObject *o2, int op) {" % richcmp_cfunc)
  1667. code.putln("switch (op) {")
  1668. class_scopes = []
  1669. cls = scope.parent_type
  1670. while cls is not None and not cls.entry.visibility == 'extern':
  1671. class_scopes.append(cls.scope)
  1672. cls = cls.scope.parent_type.base_type
  1673. assert scope in class_scopes
  1674. extern_parent = None
  1675. if cls and cls.entry.visibility == 'extern':
  1676. # need to call up into base classes as we may not know all implemented comparison methods
  1677. extern_parent = cls if cls.typeptr_cname else scope.parent_type.base_type
  1678. eq_entry = None
  1679. has_ne = False
  1680. for cmp_method in TypeSlots.richcmp_special_methods:
  1681. for class_scope in class_scopes:
  1682. entry = class_scope.lookup_here(cmp_method)
  1683. if entry is not None:
  1684. break
  1685. else:
  1686. continue
  1687. cmp_type = cmp_method.strip('_').upper() # e.g. "__eq__" -> EQ
  1688. code.putln("case Py_%s: {" % cmp_type)
  1689. if cmp_method == '__eq__':
  1690. eq_entry = entry
  1691. # Python itself does not do this optimisation, it seems...
  1692. #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_True);")
  1693. elif cmp_method == '__ne__':
  1694. has_ne = True
  1695. # Python itself does not do this optimisation, it seems...
  1696. #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);")
  1697. code.putln("return %s(o1, o2);" % entry.func_cname)
  1698. code.putln("}")
  1699. if eq_entry and not has_ne and not extern_parent:
  1700. code.putln("case Py_NE: {")
  1701. code.putln("PyObject *ret;")
  1702. # Python itself does not do this optimisation, it seems...
  1703. #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);")
  1704. code.putln("ret = %s(o1, o2);" % eq_entry.func_cname)
  1705. code.putln("if (likely(ret && ret != Py_NotImplemented)) {")
  1706. code.putln("int b = __Pyx_PyObject_IsTrue(ret); Py_DECREF(ret);")
  1707. code.putln("if (unlikely(b < 0)) return NULL;")
  1708. code.putln("ret = (b) ? Py_False : Py_True;")
  1709. code.putln("Py_INCREF(ret);")
  1710. code.putln("}")
  1711. code.putln("return ret;")
  1712. code.putln("}")
  1713. code.putln("default: {")
  1714. if extern_parent and extern_parent.typeptr_cname:
  1715. code.putln("if (likely(%s->tp_richcompare)) return %s->tp_richcompare(o1, o2, op);" % (
  1716. extern_parent.typeptr_cname, extern_parent.typeptr_cname))
  1717. code.putln("return __Pyx_NewRef(Py_NotImplemented);")
  1718. code.putln("}")
  1719. code.putln("}") # switch
  1720. code.putln("}")
  1721. def generate_getattro_function(self, scope, code):
  1722. # First try to get the attribute using __getattribute__, if defined, or
  1723. # PyObject_GenericGetAttr.
  1724. #
  1725. # If that raises an AttributeError, call the __getattr__ if defined.
  1726. #
  1727. # In both cases, defined can be in this class, or any base class.
  1728. def lookup_here_or_base(n, tp=None, extern_return=None):
  1729. # Recursive lookup
  1730. if tp is None:
  1731. tp = scope.parent_type
  1732. r = tp.scope.lookup_here(n)
  1733. if r is None:
  1734. if tp.is_external and extern_return is not None:
  1735. return extern_return
  1736. if tp.base_type is not None:
  1737. return lookup_here_or_base(n, tp.base_type)
  1738. return r
  1739. has_instance_dict = lookup_here_or_base("__dict__", extern_return="extern")
  1740. getattr_entry = lookup_here_or_base("__getattr__")
  1741. getattribute_entry = lookup_here_or_base("__getattribute__")
  1742. code.putln("")
  1743. code.putln(
  1744. "static PyObject *%s(PyObject *o, PyObject *n) {" % (
  1745. scope.mangle_internal("tp_getattro")))
  1746. if getattribute_entry is not None:
  1747. code.putln(
  1748. "PyObject *v = %s(o, n);" % (
  1749. getattribute_entry.func_cname))
  1750. else:
  1751. if not has_instance_dict and scope.parent_type.is_final_type:
  1752. # Final with no dict => use faster type attribute lookup.
  1753. code.globalstate.use_utility_code(
  1754. UtilityCode.load_cached("PyObject_GenericGetAttrNoDict", "ObjectHandling.c"))
  1755. generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttrNoDict"
  1756. elif not has_instance_dict or has_instance_dict == "extern":
  1757. # No dict in the known ancestors, but don't know about extern ancestors or subtypes.
  1758. code.globalstate.use_utility_code(
  1759. UtilityCode.load_cached("PyObject_GenericGetAttr", "ObjectHandling.c"))
  1760. generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttr"
  1761. else:
  1762. generic_getattr_cfunc = "PyObject_GenericGetAttr"
  1763. code.putln(
  1764. "PyObject *v = %s(o, n);" % generic_getattr_cfunc)
  1765. if getattr_entry is not None:
  1766. code.putln(
  1767. "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
  1768. code.putln(
  1769. "PyErr_Clear();")
  1770. code.putln(
  1771. "v = %s(o, n);" % (
  1772. getattr_entry.func_cname))
  1773. code.putln(
  1774. "}")
  1775. code.putln(
  1776. "return v;")
  1777. code.putln(
  1778. "}")
  1779. def generate_setattro_function(self, scope, code):
  1780. # Setting and deleting an attribute are both done through
  1781. # the setattro method, so we dispatch to user's __setattr__
  1782. # or __delattr__ or fall back on PyObject_GenericSetAttr.
  1783. base_type = scope.parent_type.base_type
  1784. set_entry = scope.lookup_here("__setattr__")
  1785. del_entry = scope.lookup_here("__delattr__")
  1786. code.putln("")
  1787. code.putln(
  1788. "static int %s(PyObject *o, PyObject *n, PyObject *v) {" % (
  1789. scope.mangle_internal("tp_setattro")))
  1790. code.putln(
  1791. "if (v) {")
  1792. if set_entry:
  1793. code.putln(
  1794. "return %s(o, n, v);" % (
  1795. set_entry.func_cname))
  1796. else:
  1797. self.generate_guarded_basetype_call(
  1798. base_type, None, "tp_setattro", "o, n, v", code)
  1799. code.putln(
  1800. "return PyObject_GenericSetAttr(o, n, v);")
  1801. code.putln(
  1802. "}")
  1803. code.putln(
  1804. "else {")
  1805. if del_entry:
  1806. code.putln(
  1807. "return %s(o, n);" % (
  1808. del_entry.func_cname))
  1809. else:
  1810. self.generate_guarded_basetype_call(
  1811. base_type, None, "tp_setattro", "o, n, v", code)
  1812. code.putln(
  1813. "return PyObject_GenericSetAttr(o, n, 0);")
  1814. code.putln(
  1815. "}")
  1816. code.putln(
  1817. "}")
  1818. def generate_descr_get_function(self, scope, code):
  1819. # The __get__ function of a descriptor object can be
  1820. # called with NULL for the second or third arguments
  1821. # under some circumstances, so we replace them with
  1822. # None in that case.
  1823. user_get_entry = scope.lookup_here("__get__")
  1824. code.putln("")
  1825. code.putln(
  1826. "static PyObject *%s(PyObject *o, PyObject *i, PyObject *c) {" % (
  1827. scope.mangle_internal("tp_descr_get")))
  1828. code.putln(
  1829. "PyObject *r = 0;")
  1830. code.putln(
  1831. "if (!i) i = Py_None;")
  1832. code.putln(
  1833. "if (!c) c = Py_None;")
  1834. #code.put_incref("i", py_object_type)
  1835. #code.put_incref("c", py_object_type)
  1836. code.putln(
  1837. "r = %s(o, i, c);" % (
  1838. user_get_entry.func_cname))
  1839. #code.put_decref("i", py_object_type)
  1840. #code.put_decref("c", py_object_type)
  1841. code.putln(
  1842. "return r;")
  1843. code.putln(
  1844. "}")
  1845. def generate_descr_set_function(self, scope, code):
  1846. # Setting and deleting are both done through the __set__
  1847. # method of a descriptor, so we dispatch to user's __set__
  1848. # or __delete__ or raise an exception.
  1849. base_type = scope.parent_type.base_type
  1850. user_set_entry = scope.lookup_here("__set__")
  1851. user_del_entry = scope.lookup_here("__delete__")
  1852. code.putln("")
  1853. code.putln(
  1854. "static int %s(PyObject *o, PyObject *i, PyObject *v) {" % (
  1855. scope.mangle_internal("tp_descr_set")))
  1856. code.putln(
  1857. "if (v) {")
  1858. if user_set_entry:
  1859. code.putln(
  1860. "return %s(o, i, v);" % (
  1861. user_set_entry.func_cname))
  1862. else:
  1863. self.generate_guarded_basetype_call(
  1864. base_type, None, "tp_descr_set", "o, i, v", code)
  1865. code.putln(
  1866. 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
  1867. code.putln(
  1868. "return -1;")
  1869. code.putln(
  1870. "}")
  1871. code.putln(
  1872. "else {")
  1873. if user_del_entry:
  1874. code.putln(
  1875. "return %s(o, i);" % (
  1876. user_del_entry.func_cname))
  1877. else:
  1878. self.generate_guarded_basetype_call(
  1879. base_type, None, "tp_descr_set", "o, i, v", code)
  1880. code.putln(
  1881. 'PyErr_SetString(PyExc_NotImplementedError, "__delete__");')
  1882. code.putln(
  1883. "return -1;")
  1884. code.putln(
  1885. "}")
  1886. code.putln(
  1887. "}")
  1888. def generate_property_accessors(self, cclass_scope, code):
  1889. for entry in cclass_scope.property_entries:
  1890. property_scope = entry.scope
  1891. if property_scope.defines_any(["__get__"]):
  1892. self.generate_property_get_function(entry, code)
  1893. if property_scope.defines_any(["__set__", "__del__"]):
  1894. self.generate_property_set_function(entry, code)
  1895. def generate_property_get_function(self, property_entry, code):
  1896. property_scope = property_entry.scope
  1897. property_entry.getter_cname = property_scope.parent_scope.mangle(
  1898. Naming.prop_get_prefix, property_entry.name)
  1899. get_entry = property_scope.lookup_here("__get__")
  1900. code.putln("")
  1901. code.putln(
  1902. "static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % (
  1903. property_entry.getter_cname))
  1904. code.putln(
  1905. "return %s(o);" % (
  1906. get_entry.func_cname))
  1907. code.putln(
  1908. "}")
  1909. def generate_property_set_function(self, property_entry, code):
  1910. property_scope = property_entry.scope
  1911. property_entry.setter_cname = property_scope.parent_scope.mangle(
  1912. Naming.prop_set_prefix, property_entry.name)
  1913. set_entry = property_scope.lookup_here("__set__")
  1914. del_entry = property_scope.lookup_here("__del__")
  1915. code.putln("")
  1916. code.putln(
  1917. "static int %s(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) {" % (
  1918. property_entry.setter_cname))
  1919. code.putln(
  1920. "if (v) {")
  1921. if set_entry:
  1922. code.putln(
  1923. "return %s(o, v);" % (
  1924. set_entry.func_cname))
  1925. else:
  1926. code.putln(
  1927. 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
  1928. code.putln(
  1929. "return -1;")
  1930. code.putln(
  1931. "}")
  1932. code.putln(
  1933. "else {")
  1934. if del_entry:
  1935. code.putln(
  1936. "return %s(o);" % (
  1937. del_entry.func_cname))
  1938. else:
  1939. code.putln(
  1940. 'PyErr_SetString(PyExc_NotImplementedError, "__del__");')
  1941. code.putln(
  1942. "return -1;")
  1943. code.putln(
  1944. "}")
  1945. code.putln(
  1946. "}")
  1947. def generate_typeobj_definition(self, modname, entry, code):
  1948. type = entry.type
  1949. scope = type.scope
  1950. for suite in TypeSlots.substructures:
  1951. suite.generate_substructure(scope, code)
  1952. code.putln("")
  1953. if entry.visibility == 'public':
  1954. header = "DL_EXPORT(PyTypeObject) %s = {"
  1955. else:
  1956. header = "static PyTypeObject %s = {"
  1957. #code.putln(header % scope.parent_type.typeobj_cname)
  1958. code.putln(header % type.typeobj_cname)
  1959. code.putln(
  1960. "PyVarObject_HEAD_INIT(0, 0)")
  1961. code.putln(
  1962. '"%s.%s", /*tp_name*/' % (
  1963. self.full_module_name, scope.class_name))
  1964. if type.typedef_flag:
  1965. objstruct = type.objstruct_cname
  1966. else:
  1967. objstruct = "struct %s" % type.objstruct_cname
  1968. code.putln(
  1969. "sizeof(%s), /*tp_basicsize*/" % objstruct)
  1970. code.putln(
  1971. "0, /*tp_itemsize*/")
  1972. for slot in TypeSlots.slot_table:
  1973. slot.generate(scope, code)
  1974. code.putln(
  1975. "};")
  1976. def generate_method_table(self, env, code):
  1977. if env.is_c_class_scope and not env.pyfunc_entries:
  1978. return
  1979. binding = env.directives['binding']
  1980. code.putln("")
  1981. wrapper_code_writer = code.insertion_point()
  1982. code.putln(
  1983. "static PyMethodDef %s[] = {" % (
  1984. env.method_table_cname))
  1985. for entry in env.pyfunc_entries:
  1986. if not entry.fused_cfunction and not (binding and entry.is_overridable):
  1987. code.put_pymethoddef(entry, ",", wrapper_code_writer=wrapper_code_writer)
  1988. code.putln(
  1989. "{0, 0, 0, 0}")
  1990. code.putln(
  1991. "};")
  1992. if wrapper_code_writer.getvalue():
  1993. wrapper_code_writer.putln("")
  1994. def generate_dict_getter_function(self, scope, code):
  1995. dict_attr = scope.lookup_here("__dict__")
  1996. if not dict_attr or not dict_attr.is_variable:
  1997. return
  1998. func_name = scope.mangle_internal("__dict__getter")
  1999. dict_name = dict_attr.cname
  2000. code.putln("")
  2001. code.putln("static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % func_name)
  2002. self.generate_self_cast(scope, code)
  2003. code.putln("if (unlikely(!p->%s)){" % dict_name)
  2004. code.putln("p->%s = PyDict_New();" % dict_name)
  2005. code.putln("}")
  2006. code.putln("Py_XINCREF(p->%s);" % dict_name)
  2007. code.putln("return p->%s;" % dict_name)
  2008. code.putln("}")
  2009. def generate_getset_table(self, env, code):
  2010. if env.property_entries:
  2011. code.putln("")
  2012. code.putln(
  2013. "static struct PyGetSetDef %s[] = {" %
  2014. env.getset_table_cname)
  2015. for entry in env.property_entries:
  2016. doc = entry.doc
  2017. if doc:
  2018. if doc.is_unicode:
  2019. doc = doc.as_utf8_string()
  2020. doc_code = doc.as_c_string_literal()
  2021. else:
  2022. doc_code = "0"
  2023. code.putln(
  2024. '{(char *)"%s", %s, %s, (char *)%s, 0},' % (
  2025. entry.name,
  2026. entry.getter_cname or "0",
  2027. entry.setter_cname or "0",
  2028. doc_code))
  2029. code.putln(
  2030. "{0, 0, 0, 0, 0}")
  2031. code.putln(
  2032. "};")
  2033. def create_import_star_conversion_utility_code(self, env):
  2034. # Create all conversion helpers that are needed for "import *" assignments.
  2035. # Must be done before code generation to support CythonUtilityCode.
  2036. for name, entry in sorted(env.entries.items()):
  2037. if entry.is_cglobal and entry.used:
  2038. if not entry.type.is_pyobject:
  2039. entry.type.create_from_py_utility_code(env)
  2040. def generate_import_star(self, env, code):
  2041. env.use_utility_code(UtilityCode.load_cached("CStringEquals", "StringTools.c"))
  2042. code.putln()
  2043. code.enter_cfunc_scope() # as we need labels
  2044. code.putln("static int %s(PyObject *o, PyObject* py_name, char *name) {" % Naming.import_star_set)
  2045. code.putln("static const char* internal_type_names[] = {")
  2046. for name, entry in sorted(env.entries.items()):
  2047. if entry.is_type:
  2048. code.putln('"%s",' % name)
  2049. code.putln("0")
  2050. code.putln("};")
  2051. code.putln("const char** type_name = internal_type_names;")
  2052. code.putln("while (*type_name) {")
  2053. code.putln("if (__Pyx_StrEq(name, *type_name)) {")
  2054. code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);')
  2055. code.putln('goto bad;')
  2056. code.putln("}")
  2057. code.putln("type_name++;")
  2058. code.putln("}")
  2059. old_error_label = code.new_error_label()
  2060. code.putln("if (0);") # so the first one can be "else if"
  2061. msvc_count = 0
  2062. for name, entry in sorted(env.entries.items()):
  2063. if entry.is_cglobal and entry.used and not entry.type.is_const:
  2064. msvc_count += 1
  2065. if msvc_count % 100 == 0:
  2066. code.putln("#ifdef _MSC_VER")
  2067. code.putln("if (0); /* Workaround for MSVC C1061. */")
  2068. code.putln("#endif")
  2069. code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name)
  2070. if entry.type.is_pyobject:
  2071. if entry.type.is_extension_type or entry.type.is_builtin_type:
  2072. code.putln("if (!(%s)) %s;" % (
  2073. entry.type.type_test_code("o"),
  2074. code.error_goto(entry.pos)))
  2075. code.putln("Py_INCREF(o);")
  2076. code.put_decref(entry.cname, entry.type, nanny=False)
  2077. code.putln("%s = %s;" % (
  2078. entry.cname,
  2079. PyrexTypes.typecast(entry.type, py_object_type, "o")))
  2080. elif entry.type.create_from_py_utility_code(env):
  2081. # if available, utility code was already created in self.prepare_utility_code()
  2082. code.putln(entry.type.from_py_call_code(
  2083. 'o', entry.cname, entry.pos, code))
  2084. else:
  2085. code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (
  2086. name, entry.type))
  2087. code.putln(code.error_goto(entry.pos))
  2088. code.putln("}")
  2089. code.putln("else {")
  2090. code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
  2091. code.putln("}")
  2092. code.putln("return 0;")
  2093. if code.label_used(code.error_label):
  2094. code.put_label(code.error_label)
  2095. # This helps locate the offending name.
  2096. code.put_add_traceback(self.full_module_name)
  2097. code.error_label = old_error_label
  2098. code.putln("bad:")
  2099. code.putln("return -1;")
  2100. code.putln("}")
  2101. code.putln("")
  2102. code.putln(UtilityCode.load_as_string("ImportStar", "ImportExport.c")[1])
  2103. code.exit_cfunc_scope() # done with labels
  2104. def generate_module_init_func(self, imported_modules, env, options, code):
  2105. subfunction = self.mod_init_subfunction(self.pos, self.scope, code)
  2106. code.enter_cfunc_scope(self.scope)
  2107. code.putln("")
  2108. code.putln(UtilityCode.load_as_string("PyModInitFuncType", "ModuleSetupCode.c")[0])
  2109. init_name = 'init' + (options.init_suffix or env.module_name)
  2110. header2 = "__Pyx_PyMODINIT_FUNC %s(void)" % init_name
  2111. header3 = "__Pyx_PyMODINIT_FUNC %s(void)" % self.mod_init_func_cname('PyInit', env, options)
  2112. code.putln("#if PY_MAJOR_VERSION < 3")
  2113. # Optimise for small code size as the module init function is only executed once.
  2114. code.putln("%s CYTHON_SMALL_CODE; /*proto*/" % header2)
  2115. code.putln(header2)
  2116. code.putln("#else")
  2117. code.putln("%s CYTHON_SMALL_CODE; /*proto*/" % header3)
  2118. code.putln(header3)
  2119. # CPython 3.5+ supports multi-phase module initialisation (gives access to __spec__, __file__, etc.)
  2120. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2121. code.putln("{")
  2122. code.putln("return PyModuleDef_Init(&%s);" % Naming.pymoduledef_cname)
  2123. code.putln("}")
  2124. mod_create_func = UtilityCode.load_as_string("ModuleCreationPEP489", "ModuleSetupCode.c")[1]
  2125. code.put(mod_create_func)
  2126. code.putln("")
  2127. # main module init code lives in Py_mod_exec function, not in PyInit function
  2128. code.putln("static CYTHON_SMALL_CODE int %s(PyObject *%s)" % (
  2129. self.mod_init_func_cname(Naming.pymodule_exec_func_cname, env),
  2130. Naming.pymodinit_module_arg))
  2131. code.putln("#endif") # PEP489
  2132. code.putln("#endif") # Py3
  2133. # start of module init/exec function (pre/post PEP 489)
  2134. code.putln("{")
  2135. tempdecl_code = code.insertion_point()
  2136. profile = code.globalstate.directives['profile']
  2137. linetrace = code.globalstate.directives['linetrace']
  2138. if profile or linetrace:
  2139. code.globalstate.use_utility_code(UtilityCode.load_cached("Profile", "Profile.c"))
  2140. code.put_declare_refcount_context()
  2141. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2142. # Most extension modules simply can't deal with it, and Cython isn't ready either.
  2143. # See issues listed here: https://docs.python.org/3/c-api/init.html#sub-interpreter-support
  2144. code.putln("if (%s) {" % Naming.module_cname)
  2145. # Hack: enforce single initialisation.
  2146. code.putln("if (%s == %s) return 0;" % (
  2147. Naming.module_cname,
  2148. Naming.pymodinit_module_arg,
  2149. ))
  2150. code.putln('PyErr_SetString(PyExc_RuntimeError,'
  2151. ' "Module \'%s\' has already been imported. Re-initialisation is not supported.");' %
  2152. env.module_name)
  2153. code.putln("return -1;")
  2154. code.putln("}")
  2155. code.putln("#elif PY_MAJOR_VERSION >= 3")
  2156. # Hack: enforce single initialisation also on reimports under different names on Python 3 (with PEP 3121/489).
  2157. code.putln("if (%s) return __Pyx_NewRef(%s);" % (
  2158. Naming.module_cname,
  2159. Naming.module_cname,
  2160. ))
  2161. code.putln("#endif")
  2162. if profile or linetrace:
  2163. tempdecl_code.put_trace_declarations()
  2164. code.put_trace_frame_init()
  2165. refnanny_import_code = UtilityCode.load_as_string("ImportRefnannyAPI", "ModuleSetupCode.c")[1]
  2166. code.putln(refnanny_import_code.rstrip())
  2167. code.put_setup_refcount_context(header3)
  2168. env.use_utility_code(UtilityCode.load("CheckBinaryVersion", "ModuleSetupCode.c"))
  2169. code.put_error_if_neg(self.pos, "__Pyx_check_binary_version()")
  2170. code.putln("#ifdef __Pxy_PyFrame_Initialize_Offsets")
  2171. code.putln("__Pxy_PyFrame_Initialize_Offsets();")
  2172. code.putln("#endif")
  2173. code.putln("%s = PyTuple_New(0); %s" % (
  2174. Naming.empty_tuple, code.error_goto_if_null(Naming.empty_tuple, self.pos)))
  2175. code.putln("%s = PyBytes_FromStringAndSize(\"\", 0); %s" % (
  2176. Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos)))
  2177. code.putln("%s = PyUnicode_FromStringAndSize(\"\", 0); %s" % (
  2178. Naming.empty_unicode, code.error_goto_if_null(Naming.empty_unicode, self.pos)))
  2179. for ext_type in ('CyFunction', 'FusedFunction', 'Coroutine', 'Generator', 'AsyncGen', 'StopAsyncIteration'):
  2180. code.putln("#ifdef __Pyx_%s_USED" % ext_type)
  2181. code.put_error_if_neg(self.pos, "__pyx_%s_init()" % ext_type)
  2182. code.putln("#endif")
  2183. code.putln("/*--- Library function declarations ---*/")
  2184. if env.directives['np_pythran']:
  2185. code.put_error_if_neg(self.pos, "_import_array()")
  2186. code.putln("/*--- Threads initialization code ---*/")
  2187. code.putln("#if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 "
  2188. "&& defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS")
  2189. code.putln("PyEval_InitThreads();")
  2190. code.putln("#endif")
  2191. code.putln("/*--- Module creation code ---*/")
  2192. self.generate_module_creation_code(env, options, code)
  2193. code.putln("/*--- Initialize various global constants etc. ---*/")
  2194. code.put_error_if_neg(self.pos, "__Pyx_InitGlobals()")
  2195. code.putln("#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || "
  2196. "__PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)")
  2197. code.put_error_if_neg(self.pos, "__Pyx_init_sys_getdefaultencoding_params()")
  2198. code.putln("#endif")
  2199. code.putln("if (%s%s) {" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
  2200. code.put_error_if_neg(self.pos, 'PyObject_SetAttr(%s, %s, %s)' % (
  2201. env.module_cname,
  2202. code.intern_identifier(EncodedString("__name__")),
  2203. code.intern_identifier(EncodedString("__main__"))))
  2204. code.putln("}")
  2205. # set up __file__ and __path__, then add the module to sys.modules
  2206. self.generate_module_import_setup(env, code)
  2207. if Options.cache_builtins:
  2208. code.putln("/*--- Builtin init code ---*/")
  2209. code.put_error_if_neg(self.pos, "__Pyx_InitCachedBuiltins()")
  2210. code.putln("/*--- Constants init code ---*/")
  2211. code.put_error_if_neg(self.pos, "__Pyx_InitCachedConstants()")
  2212. code.putln("/*--- Global type/function init code ---*/")
  2213. with subfunction("Global init code") as inner_code:
  2214. self.generate_global_init_code(env, inner_code)
  2215. with subfunction("Variable export code") as inner_code:
  2216. self.generate_c_variable_export_code(env, inner_code)
  2217. with subfunction("Function export code") as inner_code:
  2218. self.generate_c_function_export_code(env, inner_code)
  2219. with subfunction("Type init code") as inner_code:
  2220. self.generate_type_init_code(env, inner_code)
  2221. with subfunction("Type import code") as inner_code:
  2222. for module in imported_modules:
  2223. self.generate_type_import_code_for_module(module, env, inner_code)
  2224. with subfunction("Variable import code") as inner_code:
  2225. for module in imported_modules:
  2226. self.generate_c_variable_import_code_for_module(module, env, inner_code)
  2227. with subfunction("Function import code") as inner_code:
  2228. for module in imported_modules:
  2229. self.specialize_fused_types(module)
  2230. self.generate_c_function_import_code_for_module(module, env, inner_code)
  2231. code.putln("/*--- Execution code ---*/")
  2232. code.mark_pos(None)
  2233. code.putln("#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)")
  2234. code.put_error_if_neg(self.pos, "__Pyx_patch_abc()")
  2235. code.putln("#endif")
  2236. if profile or linetrace:
  2237. code.put_trace_call(header3, self.pos, nogil=not code.funcstate.gil_owned)
  2238. code.funcstate.can_trace = True
  2239. self.body.generate_execution_code(code)
  2240. if profile or linetrace:
  2241. code.funcstate.can_trace = False
  2242. code.put_trace_return("Py_None", nogil=not code.funcstate.gil_owned)
  2243. code.putln()
  2244. code.putln("/*--- Wrapped vars code ---*/")
  2245. self.generate_wrapped_entries_code(env, code)
  2246. code.putln()
  2247. if Options.generate_cleanup_code:
  2248. code.globalstate.use_utility_code(
  2249. UtilityCode.load_cached("RegisterModuleCleanup", "ModuleSetupCode.c"))
  2250. code.putln("if (__Pyx_RegisterCleanup()) %s" % code.error_goto(self.pos))
  2251. code.put_goto(code.return_label)
  2252. code.put_label(code.error_label)
  2253. for cname, type in code.funcstate.all_managed_temps():
  2254. code.put_xdecref(cname, type)
  2255. code.putln('if (%s) {' % env.module_cname)
  2256. code.putln('if (%s) {' % env.module_dict_cname)
  2257. code.put_add_traceback("init %s" % env.qualified_name)
  2258. code.globalstate.use_utility_code(Nodes.traceback_utility_code)
  2259. # Module reference and module dict are in global variables which might still be needed
  2260. # for cleanup, atexit code, etc., so leaking is better than crashing.
  2261. # At least clearing the module dict here might be a good idea, but could still break
  2262. # user code in atexit or other global registries.
  2263. ##code.put_decref_clear(env.module_dict_cname, py_object_type, nanny=False)
  2264. code.putln('}')
  2265. code.put_decref_clear(env.module_cname, py_object_type, nanny=False, clear_before_decref=True)
  2266. code.putln('} else if (!PyErr_Occurred()) {')
  2267. code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' % env.qualified_name)
  2268. code.putln('}')
  2269. code.put_label(code.return_label)
  2270. code.put_finish_refcount_context()
  2271. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2272. code.putln("return (%s != NULL) ? 0 : -1;" % env.module_cname)
  2273. code.putln("#elif PY_MAJOR_VERSION >= 3")
  2274. code.putln("return %s;" % env.module_cname)
  2275. code.putln("#else")
  2276. code.putln("return;")
  2277. code.putln("#endif")
  2278. code.putln('}')
  2279. tempdecl_code.put_temp_declarations(code.funcstate)
  2280. code.exit_cfunc_scope()
  2281. def mod_init_subfunction(self, pos, scope, orig_code):
  2282. """
  2283. Return a context manager that allows deviating the module init code generation
  2284. into a separate function and instead inserts a call to it.
  2285. Can be reused sequentially to create multiple functions.
  2286. The functions get inserted at the point where the context manager was created.
  2287. The call gets inserted where the context manager is used (on entry).
  2288. """
  2289. prototypes = orig_code.insertion_point()
  2290. prototypes.putln("")
  2291. function_code = orig_code.insertion_point()
  2292. function_code.putln("")
  2293. class ModInitSubfunction(object):
  2294. def __init__(self, code_type):
  2295. cname = '_'.join(code_type.lower().split())
  2296. assert re.match("^[a-z0-9_]+$", cname)
  2297. self.cfunc_name = "__Pyx_modinit_%s" % cname
  2298. self.description = code_type
  2299. self.tempdecl_code = None
  2300. self.call_code = None
  2301. def __enter__(self):
  2302. self.call_code = orig_code.insertion_point()
  2303. code = function_code
  2304. code.enter_cfunc_scope(scope)
  2305. prototypes.putln("static CYTHON_SMALL_CODE int %s(void); /*proto*/" % self.cfunc_name)
  2306. code.putln("static int %s(void) {" % self.cfunc_name)
  2307. code.put_declare_refcount_context()
  2308. self.tempdecl_code = code.insertion_point()
  2309. code.put_setup_refcount_context(self.cfunc_name)
  2310. # Leave a grepable marker that makes it easy to find the generator source.
  2311. code.putln("/*--- %s ---*/" % self.description)
  2312. return code
  2313. def __exit__(self, *args):
  2314. code = function_code
  2315. code.put_finish_refcount_context()
  2316. code.putln("return 0;")
  2317. self.tempdecl_code.put_temp_declarations(code.funcstate)
  2318. self.tempdecl_code = None
  2319. needs_error_handling = code.label_used(code.error_label)
  2320. if needs_error_handling:
  2321. code.put_label(code.error_label)
  2322. for cname, type in code.funcstate.all_managed_temps():
  2323. code.put_xdecref(cname, type)
  2324. code.put_finish_refcount_context()
  2325. code.putln("return -1;")
  2326. code.putln("}")
  2327. code.exit_cfunc_scope()
  2328. code.putln("")
  2329. if needs_error_handling:
  2330. self.call_code.putln(
  2331. self.call_code.error_goto_if_neg("%s()" % self.cfunc_name, pos))
  2332. else:
  2333. self.call_code.putln("(void)%s();" % self.cfunc_name)
  2334. self.call_code = None
  2335. return ModInitSubfunction
  2336. def generate_module_import_setup(self, env, code):
  2337. module_path = env.directives['set_initial_path']
  2338. if module_path == 'SOURCEFILE':
  2339. module_path = self.pos[0].filename
  2340. if module_path:
  2341. code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {')
  2342. code.putln('if (PyObject_SetAttrString(%s, "__file__", %s) < 0) %s;' % (
  2343. env.module_cname,
  2344. code.globalstate.get_py_string_const(
  2345. EncodedString(decode_filename(module_path))).cname,
  2346. code.error_goto(self.pos)))
  2347. code.putln("}")
  2348. if env.is_package:
  2349. # set __path__ to mark the module as package
  2350. code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {')
  2351. temp = code.funcstate.allocate_temp(py_object_type, True)
  2352. code.putln('%s = Py_BuildValue("[O]", %s); %s' % (
  2353. temp,
  2354. code.globalstate.get_py_string_const(
  2355. EncodedString(decode_filename(
  2356. os.path.dirname(module_path)))).cname,
  2357. code.error_goto_if_null(temp, self.pos)))
  2358. code.put_gotref(temp)
  2359. code.putln(
  2360. 'if (PyObject_SetAttrString(%s, "__path__", %s) < 0) %s;' % (
  2361. env.module_cname, temp, code.error_goto(self.pos)))
  2362. code.put_decref_clear(temp, py_object_type)
  2363. code.funcstate.release_temp(temp)
  2364. code.putln("}")
  2365. elif env.is_package:
  2366. # packages require __path__, so all we can do is try to figure
  2367. # out the module path at runtime by rerunning the import lookup
  2368. code.putln("if (!CYTHON_PEP489_MULTI_PHASE_INIT) {")
  2369. code.globalstate.use_utility_code(UtilityCode.load(
  2370. "SetPackagePathFromImportLib", "ImportExport.c"))
  2371. code.putln(code.error_goto_if_neg(
  2372. '__Pyx_SetPackagePathFromImportLib(%s)' % (
  2373. code.globalstate.get_py_string_const(
  2374. EncodedString(self.full_module_name)).cname),
  2375. self.pos))
  2376. code.putln("}")
  2377. # CPython may not have put us into sys.modules yet, but relative imports and reimports require it
  2378. fq_module_name = self.full_module_name
  2379. if fq_module_name.endswith('.__init__'):
  2380. fq_module_name = fq_module_name[:-len('.__init__')]
  2381. code.putln("#if PY_MAJOR_VERSION >= 3")
  2382. code.putln("{")
  2383. code.putln("PyObject *modules = PyImport_GetModuleDict(); %s" %
  2384. code.error_goto_if_null("modules", self.pos))
  2385. code.putln('if (!PyDict_GetItemString(modules, "%s")) {' % fq_module_name)
  2386. code.putln(code.error_goto_if_neg('PyDict_SetItemString(modules, "%s", %s)' % (
  2387. fq_module_name, env.module_cname), self.pos))
  2388. code.putln("}")
  2389. code.putln("}")
  2390. code.putln("#endif")
  2391. def generate_module_cleanup_func(self, env, code):
  2392. if not Options.generate_cleanup_code:
  2393. return
  2394. code.putln('static void %s(CYTHON_UNUSED PyObject *self) {' %
  2395. Naming.cleanup_cname)
  2396. code.enter_cfunc_scope(env)
  2397. if Options.generate_cleanup_code >= 2:
  2398. code.putln("/*--- Global cleanup code ---*/")
  2399. rev_entries = list(env.var_entries)
  2400. rev_entries.reverse()
  2401. for entry in rev_entries:
  2402. if entry.visibility != 'extern':
  2403. if entry.type.is_pyobject and entry.used:
  2404. code.put_xdecref_clear(
  2405. entry.cname, entry.type,
  2406. clear_before_decref=True,
  2407. nanny=False)
  2408. code.putln("__Pyx_CleanupGlobals();")
  2409. if Options.generate_cleanup_code >= 3:
  2410. code.putln("/*--- Type import cleanup code ---*/")
  2411. for ext_type in sorted(env.types_imported, key=operator.attrgetter('typeptr_cname')):
  2412. code.put_xdecref_clear(
  2413. ext_type.typeptr_cname, ext_type,
  2414. clear_before_decref=True,
  2415. nanny=False)
  2416. if Options.cache_builtins:
  2417. code.putln("/*--- Builtin cleanup code ---*/")
  2418. for entry in env.cached_builtins:
  2419. code.put_xdecref_clear(
  2420. entry.cname, PyrexTypes.py_object_type,
  2421. clear_before_decref=True,
  2422. nanny=False)
  2423. code.putln("/*--- Intern cleanup code ---*/")
  2424. code.put_decref_clear(Naming.empty_tuple,
  2425. PyrexTypes.py_object_type,
  2426. clear_before_decref=True,
  2427. nanny=False)
  2428. for entry in env.c_class_entries:
  2429. cclass_type = entry.type
  2430. if cclass_type.is_external or cclass_type.base_type:
  2431. continue
  2432. if cclass_type.scope.directives.get('freelist', 0):
  2433. scope = cclass_type.scope
  2434. freelist_name = scope.mangle_internal(Naming.freelist_name)
  2435. freecount_name = scope.mangle_internal(Naming.freecount_name)
  2436. code.putln("while (%s > 0) {" % freecount_name)
  2437. code.putln("PyObject* o = (PyObject*)%s[--%s];" % (
  2438. freelist_name, freecount_name))
  2439. code.putln("(*Py_TYPE(o)->tp_free)(o);")
  2440. code.putln("}")
  2441. # for entry in env.pynum_entries:
  2442. # code.put_decref_clear(entry.cname,
  2443. # PyrexTypes.py_object_type,
  2444. # nanny=False)
  2445. # for entry in env.all_pystring_entries:
  2446. # if entry.is_interned:
  2447. # code.put_decref_clear(entry.pystring_cname,
  2448. # PyrexTypes.py_object_type,
  2449. # nanny=False)
  2450. # for entry in env.default_entries:
  2451. # if entry.type.is_pyobject and entry.used:
  2452. # code.putln("Py_DECREF(%s); %s = 0;" % (
  2453. # code.entry_as_pyobject(entry), entry.cname))
  2454. if Options.pre_import is not None:
  2455. code.put_decref_clear(Naming.preimport_cname, py_object_type,
  2456. nanny=False, clear_before_decref=True)
  2457. for cname in [env.module_dict_cname, Naming.cython_runtime_cname, Naming.builtins_cname]:
  2458. code.put_decref_clear(cname, py_object_type, nanny=False, clear_before_decref=True)
  2459. def generate_main_method(self, env, code):
  2460. module_is_main = "%s%s" % (Naming.module_is_main, self.full_module_name.replace('.', '__'))
  2461. if Options.embed == "main":
  2462. wmain = "wmain"
  2463. else:
  2464. wmain = Options.embed
  2465. main_method = UtilityCode.load_cached("MainFunction", "Embed.c")
  2466. code.globalstate.use_utility_code(
  2467. main_method.specialize(
  2468. module_name=env.module_name,
  2469. module_is_main=module_is_main,
  2470. main_method=Options.embed,
  2471. wmain_method=wmain))
  2472. def mod_init_func_cname(self, prefix, env, options=None):
  2473. return '%s_%s' % (prefix, options and options.init_suffix or env.module_name)
  2474. def generate_pymoduledef_struct(self, env, options, code):
  2475. if env.doc:
  2476. doc = "%s" % code.get_string_const(env.doc)
  2477. else:
  2478. doc = "0"
  2479. if Options.generate_cleanup_code:
  2480. cleanup_func = "(freefunc)%s" % Naming.cleanup_cname
  2481. else:
  2482. cleanup_func = 'NULL'
  2483. code.putln("")
  2484. code.putln("#if PY_MAJOR_VERSION >= 3")
  2485. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2486. exec_func_cname = self.mod_init_func_cname(Naming.pymodule_exec_func_cname, env)
  2487. code.putln("static PyObject* %s(PyObject *spec, PyModuleDef *def); /*proto*/" %
  2488. Naming.pymodule_create_func_cname)
  2489. code.putln("static int %s(PyObject* module); /*proto*/" % exec_func_cname)
  2490. code.putln("static PyModuleDef_Slot %s[] = {" % Naming.pymoduledef_slots_cname)
  2491. code.putln("{Py_mod_create, (void*)%s}," % Naming.pymodule_create_func_cname)
  2492. code.putln("{Py_mod_exec, (void*)%s}," % exec_func_cname)
  2493. code.putln("{0, NULL}")
  2494. code.putln("};")
  2495. code.putln("#endif")
  2496. code.putln("")
  2497. code.putln("static struct PyModuleDef %s = {" % Naming.pymoduledef_cname)
  2498. code.putln(" PyModuleDef_HEAD_INIT,")
  2499. code.putln(' "%s",' % (options.module_name or env.module_name))
  2500. code.putln(" %s, /* m_doc */" % doc)
  2501. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2502. code.putln(" 0, /* m_size */")
  2503. code.putln("#else")
  2504. code.putln(" -1, /* m_size */")
  2505. code.putln("#endif")
  2506. code.putln(" %s /* m_methods */," % env.method_table_cname)
  2507. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2508. code.putln(" %s, /* m_slots */" % Naming.pymoduledef_slots_cname)
  2509. code.putln("#else")
  2510. code.putln(" NULL, /* m_reload */")
  2511. code.putln("#endif")
  2512. code.putln(" NULL, /* m_traverse */")
  2513. code.putln(" NULL, /* m_clear */")
  2514. code.putln(" %s /* m_free */" % cleanup_func)
  2515. code.putln("};")
  2516. code.putln("#endif")
  2517. def generate_module_creation_code(self, env, options, code):
  2518. # Generate code to create the module object and
  2519. # install the builtins.
  2520. if env.doc:
  2521. doc = "%s" % code.get_string_const(env.doc)
  2522. else:
  2523. doc = "0"
  2524. code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
  2525. code.putln("%s = %s;" % (
  2526. env.module_cname,
  2527. Naming.pymodinit_module_arg))
  2528. code.put_incref(env.module_cname, py_object_type, nanny=False)
  2529. code.putln("#else")
  2530. code.putln("#if PY_MAJOR_VERSION < 3")
  2531. code.putln(
  2532. '%s = Py_InitModule4("%s", %s, %s, 0, PYTHON_API_VERSION); Py_XINCREF(%s);' % (
  2533. env.module_cname,
  2534. options.module_name or env.module_name,
  2535. env.method_table_cname,
  2536. doc,
  2537. env.module_cname))
  2538. code.putln("#else")
  2539. code.putln(
  2540. "%s = PyModule_Create(&%s);" % (
  2541. env.module_cname,
  2542. Naming.pymoduledef_cname))
  2543. code.putln("#endif")
  2544. code.putln(code.error_goto_if_null(env.module_cname, self.pos))
  2545. code.putln("#endif") # CYTHON_PEP489_MULTI_PHASE_INIT
  2546. code.putln(
  2547. "%s = PyModule_GetDict(%s); %s" % (
  2548. env.module_dict_cname, env.module_cname,
  2549. code.error_goto_if_null(env.module_dict_cname, self.pos)))
  2550. code.put_incref(env.module_dict_cname, py_object_type, nanny=False)
  2551. code.putln(
  2552. '%s = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); %s' % (
  2553. Naming.builtins_cname,
  2554. code.error_goto_if_null(Naming.builtins_cname, self.pos)))
  2555. code.put_incref(Naming.builtins_cname, py_object_type, nanny=False)
  2556. code.putln(
  2557. '%s = PyImport_AddModule((char *) "cython_runtime"); %s' % (
  2558. Naming.cython_runtime_cname,
  2559. code.error_goto_if_null(Naming.cython_runtime_cname, self.pos)))
  2560. code.put_incref(Naming.cython_runtime_cname, py_object_type, nanny=False)
  2561. code.putln(
  2562. 'if (PyObject_SetAttrString(%s, "__builtins__", %s) < 0) %s' % (
  2563. env.module_cname,
  2564. Naming.builtins_cname,
  2565. code.error_goto(self.pos)))
  2566. if Options.pre_import is not None:
  2567. code.putln(
  2568. '%s = PyImport_AddModule("%s"); %s' % (
  2569. Naming.preimport_cname,
  2570. Options.pre_import,
  2571. code.error_goto_if_null(Naming.preimport_cname, self.pos)))
  2572. code.put_incref(Naming.preimport_cname, py_object_type, nanny=False)
  2573. def generate_global_init_code(self, env, code):
  2574. # Generate code to initialise global PyObject *
  2575. # variables to None.
  2576. for entry in env.var_entries:
  2577. if entry.visibility != 'extern':
  2578. if entry.used:
  2579. entry.type.global_init_code(entry, code)
  2580. def generate_wrapped_entries_code(self, env, code):
  2581. for name, entry in sorted(env.entries.items()):
  2582. if (entry.create_wrapper
  2583. and not entry.is_type
  2584. and entry.scope is env):
  2585. if not entry.type.create_to_py_utility_code(env):
  2586. error(entry.pos, "Cannot convert '%s' to Python object" % entry.type)
  2587. code.putln("{")
  2588. code.putln("PyObject* wrapped = %s(%s);" % (
  2589. entry.type.to_py_function,
  2590. entry.cname))
  2591. code.putln(code.error_goto_if_null("wrapped", entry.pos))
  2592. code.putln(
  2593. 'if (PyObject_SetAttrString(%s, "%s", wrapped) < 0) %s;' % (
  2594. env.module_cname,
  2595. name,
  2596. code.error_goto(entry.pos)))
  2597. code.putln("}")
  2598. def generate_c_variable_export_code(self, env, code):
  2599. # Generate code to create PyCFunction wrappers for exported C functions.
  2600. entries = []
  2601. for entry in env.var_entries:
  2602. if (entry.api
  2603. or entry.defined_in_pxd
  2604. or (Options.cimport_from_pyx and not entry.visibility == 'extern')):
  2605. entries.append(entry)
  2606. if entries:
  2607. env.use_utility_code(UtilityCode.load_cached("VoidPtrExport", "ImportExport.c"))
  2608. for entry in entries:
  2609. signature = entry.type.empty_declaration_code()
  2610. name = code.intern_identifier(entry.name)
  2611. code.putln('if (__Pyx_ExportVoidPtr(%s, (void *)&%s, "%s") < 0) %s' % (
  2612. name, entry.cname, signature,
  2613. code.error_goto(self.pos)))
  2614. def generate_c_function_export_code(self, env, code):
  2615. # Generate code to create PyCFunction wrappers for exported C functions.
  2616. entries = []
  2617. for entry in env.cfunc_entries:
  2618. if (entry.api
  2619. or entry.defined_in_pxd
  2620. or (Options.cimport_from_pyx and not entry.visibility == 'extern')):
  2621. entries.append(entry)
  2622. if entries:
  2623. env.use_utility_code(
  2624. UtilityCode.load_cached("FunctionExport", "ImportExport.c"))
  2625. # Note: while this looks like it could be more cheaply stored and read from a struct array,
  2626. # investigation shows that the resulting binary is smaller with repeated functions calls.
  2627. for entry in entries:
  2628. signature = entry.type.signature_string()
  2629. code.putln('if (__Pyx_ExportFunction("%s", (void (*)(void))%s, "%s") < 0) %s' % (
  2630. entry.name,
  2631. entry.cname,
  2632. signature,
  2633. code.error_goto(self.pos)))
  2634. def generate_type_import_code_for_module(self, module, env, code):
  2635. # Generate type import code for all exported extension types in
  2636. # an imported module.
  2637. #if module.c_class_entries:
  2638. with ModuleImportGenerator(code) as import_generator:
  2639. for entry in module.c_class_entries:
  2640. if entry.defined_in_pxd:
  2641. self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator)
  2642. def specialize_fused_types(self, pxd_env):
  2643. """
  2644. If fused c(p)def functions are defined in an imported pxd, but not
  2645. used in this implementation file, we still have fused entries and
  2646. not specialized ones. This method replaces any fused entries with their
  2647. specialized ones.
  2648. """
  2649. for entry in pxd_env.cfunc_entries[:]:
  2650. if entry.type.is_fused:
  2651. # This call modifies the cfunc_entries in-place
  2652. entry.type.get_all_specialized_function_types()
  2653. def generate_c_variable_import_code_for_module(self, module, env, code):
  2654. # Generate import code for all exported C functions in a cimported module.
  2655. entries = []
  2656. for entry in module.var_entries:
  2657. if entry.defined_in_pxd:
  2658. entries.append(entry)
  2659. if entries:
  2660. env.use_utility_code(
  2661. UtilityCode.load_cached("VoidPtrImport", "ImportExport.c"))
  2662. temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  2663. code.putln(
  2664. '%s = PyImport_ImportModule("%s"); if (!%s) %s' % (
  2665. temp,
  2666. module.qualified_name,
  2667. temp,
  2668. code.error_goto(self.pos)))
  2669. code.put_gotref(temp)
  2670. for entry in entries:
  2671. if env is module:
  2672. cname = entry.cname
  2673. else:
  2674. cname = module.mangle(Naming.varptr_prefix, entry.name)
  2675. signature = entry.type.empty_declaration_code()
  2676. code.putln(
  2677. 'if (__Pyx_ImportVoidPtr_%s(%s, "%s", (void **)&%s, "%s") < 0) %s' % (
  2678. Naming.cyversion,
  2679. temp, entry.name, cname, signature,
  2680. code.error_goto(self.pos)))
  2681. code.put_decref_clear(temp, py_object_type)
  2682. code.funcstate.release_temp(temp)
  2683. def generate_c_function_import_code_for_module(self, module, env, code):
  2684. # Generate import code for all exported C functions in a cimported module.
  2685. entries = []
  2686. for entry in module.cfunc_entries:
  2687. if entry.defined_in_pxd and entry.used:
  2688. entries.append(entry)
  2689. if entries:
  2690. env.use_utility_code(
  2691. UtilityCode.load_cached("FunctionImport", "ImportExport.c"))
  2692. temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  2693. code.putln(
  2694. '%s = PyImport_ImportModule("%s"); if (!%s) %s' % (
  2695. temp,
  2696. module.qualified_name,
  2697. temp,
  2698. code.error_goto(self.pos)))
  2699. code.put_gotref(temp)
  2700. for entry in entries:
  2701. code.putln(
  2702. 'if (__Pyx_ImportFunction_%s(%s, "%s", (void (**)(void))&%s, "%s") < 0) %s' % (
  2703. Naming.cyversion,
  2704. temp,
  2705. entry.name,
  2706. entry.cname,
  2707. entry.type.signature_string(),
  2708. code.error_goto(self.pos)))
  2709. code.put_decref_clear(temp, py_object_type)
  2710. code.funcstate.release_temp(temp)
  2711. def generate_type_init_code(self, env, code):
  2712. # Generate type import code for extern extension types
  2713. # and type ready code for non-extern ones.
  2714. with ModuleImportGenerator(code) as import_generator:
  2715. for entry in env.c_class_entries:
  2716. if entry.visibility == 'extern' and not entry.utility_code_definition:
  2717. self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator)
  2718. else:
  2719. self.generate_base_type_import_code(env, entry, code, import_generator)
  2720. self.generate_exttype_vtable_init_code(entry, code)
  2721. if entry.type.early_init:
  2722. self.generate_type_ready_code(entry, code)
  2723. def generate_base_type_import_code(self, env, entry, code, import_generator):
  2724. base_type = entry.type.base_type
  2725. if (base_type and base_type.module_name != env.qualified_name and not
  2726. base_type.is_builtin_type and not entry.utility_code_definition):
  2727. self.generate_type_import_code(env, base_type, self.pos, code, import_generator)
  2728. def generate_type_import_code(self, env, type, pos, code, import_generator):
  2729. # If not already done, generate code to import the typeobject of an
  2730. # extension type defined in another module, and extract its C method
  2731. # table pointer if any.
  2732. if type in env.types_imported:
  2733. return
  2734. if type.name not in Code.ctypedef_builtins_map:
  2735. # see corresponding condition in generate_type_import_call() below!
  2736. code.globalstate.use_utility_code(
  2737. UtilityCode.load_cached("TypeImport", "ImportExport.c"))
  2738. self.generate_type_import_call(type, code, import_generator, error_pos=pos)
  2739. if type.vtabptr_cname:
  2740. code.globalstate.use_utility_code(
  2741. UtilityCode.load_cached('GetVTable', 'ImportExport.c'))
  2742. code.putln("%s = (struct %s*)__Pyx_GetVtable(%s->tp_dict); %s" % (
  2743. type.vtabptr_cname,
  2744. type.vtabstruct_cname,
  2745. type.typeptr_cname,
  2746. code.error_goto_if_null(type.vtabptr_cname, pos)))
  2747. env.types_imported.add(type)
  2748. def generate_type_import_call(self, type, code, import_generator, error_code=None, error_pos=None):
  2749. if type.typedef_flag:
  2750. objstruct = type.objstruct_cname
  2751. else:
  2752. objstruct = "struct %s" % type.objstruct_cname
  2753. sizeof_objstruct = objstruct
  2754. module_name = type.module_name
  2755. condition = replacement = None
  2756. if module_name not in ('__builtin__', 'builtins'):
  2757. module_name = '"%s"' % module_name
  2758. elif type.name in Code.ctypedef_builtins_map:
  2759. # Fast path for special builtins, don't actually import
  2760. ctypename = Code.ctypedef_builtins_map[type.name]
  2761. code.putln('%s = %s;' % (type.typeptr_cname, ctypename))
  2762. return
  2763. else:
  2764. module_name = '__Pyx_BUILTIN_MODULE_NAME'
  2765. if type.name in Code.non_portable_builtins_map:
  2766. condition, replacement = Code.non_portable_builtins_map[type.name]
  2767. if objstruct in Code.basicsize_builtins_map:
  2768. # Some builtin types have a tp_basicsize which differs from sizeof(...):
  2769. sizeof_objstruct = Code.basicsize_builtins_map[objstruct]
  2770. if not error_code:
  2771. assert error_pos is not None
  2772. error_code = code.error_goto(error_pos)
  2773. module = import_generator.imported_module(module_name, error_code)
  2774. code.put('%s = __Pyx_ImportType_%s(%s, %s,' % (
  2775. type.typeptr_cname,
  2776. Naming.cyversion,
  2777. module,
  2778. module_name))
  2779. if condition and replacement:
  2780. code.putln("") # start in new line
  2781. code.putln("#if %s" % condition)
  2782. code.putln('"%s",' % replacement)
  2783. code.putln("#else")
  2784. code.putln('"%s",' % type.name)
  2785. code.putln("#endif")
  2786. else:
  2787. code.put(' "%s", ' % type.name)
  2788. if sizeof_objstruct != objstruct:
  2789. if not condition:
  2790. code.putln("") # start in new line
  2791. code.putln("#if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000")
  2792. code.putln('sizeof(%s), __PYX_GET_STRUCT_ALIGNMENT_%s(%s),' % (
  2793. objstruct, Naming.cyversion, objstruct))
  2794. code.putln("#else")
  2795. code.putln('sizeof(%s), __PYX_GET_STRUCT_ALIGNMENT_%s(%s),' % (
  2796. sizeof_objstruct, Naming.cyversion, sizeof_objstruct))
  2797. code.putln("#endif")
  2798. else:
  2799. code.put('sizeof(%s), __PYX_GET_STRUCT_ALIGNMENT_%s(%s),' % (
  2800. objstruct, Naming.cyversion, objstruct))
  2801. # check_size
  2802. if type.check_size and type.check_size in ('error', 'warn', 'ignore'):
  2803. check_size = type.check_size
  2804. elif not type.is_external or type.is_subclassed:
  2805. check_size = 'error'
  2806. else:
  2807. raise RuntimeError("invalid value for check_size '%s' when compiling %s.%s" % (
  2808. type.check_size, module_name, type.name))
  2809. code.put('__Pyx_ImportType_CheckSize_%s_%s);' % (
  2810. check_size.title(), Naming.cyversion))
  2811. code.putln(' if (!%s) %s' % (type.typeptr_cname, error_code))
  2812. def generate_type_ready_code(self, entry, code):
  2813. Nodes.CClassDefNode.generate_type_ready_code(entry, code)
  2814. def generate_exttype_vtable_init_code(self, entry, code):
  2815. # Generate code to initialise the C method table of an
  2816. # extension type.
  2817. type = entry.type
  2818. if type.vtable_cname:
  2819. code.putln(
  2820. "%s = &%s;" % (
  2821. type.vtabptr_cname,
  2822. type.vtable_cname))
  2823. if type.base_type and type.base_type.vtabptr_cname:
  2824. code.putln(
  2825. "%s.%s = *%s;" % (
  2826. type.vtable_cname,
  2827. Naming.obj_base_cname,
  2828. type.base_type.vtabptr_cname))
  2829. c_method_entries = [
  2830. entry for entry in type.scope.cfunc_entries
  2831. if entry.func_cname]
  2832. if c_method_entries:
  2833. for meth_entry in c_method_entries:
  2834. cast = meth_entry.type.signature_cast_string()
  2835. code.putln(
  2836. "%s.%s = %s%s;" % (
  2837. type.vtable_cname,
  2838. meth_entry.cname,
  2839. cast,
  2840. meth_entry.func_cname))
  2841. class ModuleImportGenerator(object):
  2842. """
  2843. Helper to generate module import while importing external types.
  2844. This is used to avoid excessive re-imports of external modules when multiple types are looked up.
  2845. """
  2846. def __init__(self, code, imported_modules=None):
  2847. self.code = code
  2848. self.imported = {}
  2849. if imported_modules:
  2850. for name, cname in imported_modules.items():
  2851. self.imported['"%s"' % name] = cname
  2852. self.temps = [] # remember original import order for freeing
  2853. def imported_module(self, module_name_string, error_code):
  2854. if module_name_string in self.imported:
  2855. return self.imported[module_name_string]
  2856. code = self.code
  2857. temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  2858. self.temps.append(temp)
  2859. code.putln('%s = PyImport_ImportModule(%s); if (unlikely(!%s)) %s' % (
  2860. temp, module_name_string, temp, error_code))
  2861. code.put_gotref(temp)
  2862. self.imported[module_name_string] = temp
  2863. return temp
  2864. def __enter__(self):
  2865. return self
  2866. def __exit__(self, *exc):
  2867. code = self.code
  2868. for temp in self.temps:
  2869. code.put_decref_clear(temp, py_object_type)
  2870. code.funcstate.release_temp(temp)
  2871. def generate_cfunction_declaration(entry, env, code, definition):
  2872. from_cy_utility = entry.used and entry.utility_code_definition
  2873. if entry.used and entry.inline_func_in_pxd or (not entry.in_cinclude and (
  2874. definition or entry.defined_in_pxd or entry.visibility == 'extern' or from_cy_utility)):
  2875. if entry.visibility == 'extern':
  2876. storage_class = Naming.extern_c_macro
  2877. dll_linkage = "DL_IMPORT"
  2878. elif entry.visibility == 'public':
  2879. storage_class = Naming.extern_c_macro
  2880. dll_linkage = None
  2881. elif entry.visibility == 'private':
  2882. storage_class = "static"
  2883. dll_linkage = None
  2884. else:
  2885. storage_class = "static"
  2886. dll_linkage = None
  2887. type = entry.type
  2888. if entry.defined_in_pxd and not definition:
  2889. storage_class = "static"
  2890. dll_linkage = None
  2891. type = CPtrType(type)
  2892. header = type.declaration_code(
  2893. entry.cname, dll_linkage=dll_linkage)
  2894. modifiers = code.build_function_modifiers(entry.func_modifiers)
  2895. code.putln("%s %s%s; /*proto*/" % (
  2896. storage_class,
  2897. modifiers,
  2898. header))
  2899. #------------------------------------------------------------------------------------
  2900. #
  2901. # Runtime support code
  2902. #
  2903. #------------------------------------------------------------------------------------
  2904. refnanny_utility_code = UtilityCode.load("Refnanny", "ModuleSetupCode.c")
  2905. packed_struct_utility_code = UtilityCode(proto="""
  2906. #if defined(__GNUC__)
  2907. #define __Pyx_PACKED __attribute__((__packed__))
  2908. #else
  2909. #define __Pyx_PACKED
  2910. #endif
  2911. """, impl="", proto_block='utility_code_proto_before_types')
  2912. capsule_utility_code = UtilityCode.load("Capsule")