ModuleNode.py 139 KB

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