generator.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. #!/usr/bin/python -u
  2. #
  3. # generate python wrappers from the XML API description
  4. #
  5. functions = {}
  6. enums = {} # { enumType: { enumConstant: enumValue } }
  7. import os
  8. import sys
  9. import string
  10. if __name__ == "__main__":
  11. # launched as a script
  12. srcPref = os.path.dirname(sys.argv[0])
  13. else:
  14. # imported
  15. srcPref = os.path.dirname(__file__)
  16. #######################################################################
  17. #
  18. # That part if purely the API acquisition phase from the
  19. # XML API description
  20. #
  21. #######################################################################
  22. import os
  23. import xml.sax
  24. debug = 0
  25. def getparser():
  26. # Attach parser to an unmarshalling object. return both objects.
  27. target = docParser()
  28. parser = xml.sax.make_parser()
  29. parser.setContentHandler(target)
  30. return parser, target
  31. class docParser(xml.sax.handler.ContentHandler):
  32. def __init__(self):
  33. self._methodname = None
  34. self._data = []
  35. self.in_function = 0
  36. self.startElement = self.start
  37. self.endElement = self.end
  38. self.characters = self.data
  39. def close(self):
  40. if debug:
  41. print "close"
  42. def getmethodname(self):
  43. return self._methodname
  44. def data(self, text):
  45. if debug:
  46. print "data %s" % text
  47. self._data.append(text)
  48. def start(self, tag, attrs):
  49. if debug:
  50. print "start %s, %s" % (tag, attrs)
  51. if tag == 'function':
  52. self._data = []
  53. self.in_function = 1
  54. self.function = None
  55. self.function_cond = None
  56. self.function_args = []
  57. self.function_descr = None
  58. self.function_return = None
  59. self.function_file = None
  60. if attrs.has_key('name'):
  61. self.function = attrs['name']
  62. if attrs.has_key('file'):
  63. self.function_file = attrs['file']
  64. elif tag == 'cond':
  65. self._data = []
  66. elif tag == 'info':
  67. self._data = []
  68. elif tag == 'arg':
  69. if self.in_function == 1:
  70. self.function_arg_name = None
  71. self.function_arg_type = None
  72. self.function_arg_info = None
  73. if attrs.has_key('name'):
  74. self.function_arg_name = attrs['name']
  75. if attrs.has_key('type'):
  76. self.function_arg_type = attrs['type']
  77. if attrs.has_key('info'):
  78. self.function_arg_info = attrs['info']
  79. elif tag == 'return':
  80. if self.in_function == 1:
  81. self.function_return_type = None
  82. self.function_return_info = None
  83. self.function_return_field = None
  84. if attrs.has_key('type'):
  85. self.function_return_type = attrs['type']
  86. if attrs.has_key('info'):
  87. self.function_return_info = attrs['info']
  88. if attrs.has_key('field'):
  89. self.function_return_field = attrs['field']
  90. elif tag == 'enum':
  91. enum(attrs['type'],attrs['name'],attrs['value'])
  92. def end(self, tag):
  93. if debug:
  94. print "end %s" % tag
  95. if tag == 'function':
  96. if self.function != None:
  97. function(self.function, self.function_descr,
  98. self.function_return, self.function_args,
  99. self.function_file, self.function_cond)
  100. self.in_function = 0
  101. elif tag == 'arg':
  102. if self.in_function == 1:
  103. self.function_args.append([self.function_arg_name,
  104. self.function_arg_type,
  105. self.function_arg_info])
  106. elif tag == 'return':
  107. if self.in_function == 1:
  108. self.function_return = [self.function_return_type,
  109. self.function_return_info,
  110. self.function_return_field]
  111. elif tag == 'info':
  112. str = ''
  113. for c in self._data:
  114. str = str + c
  115. if self.in_function == 1:
  116. self.function_descr = str
  117. elif tag == 'cond':
  118. str = ''
  119. for c in self._data:
  120. str = str + c
  121. if self.in_function == 1:
  122. self.function_cond = str
  123. def function(name, desc, ret, args, file, cond):
  124. functions[name] = (desc, ret, args, file, cond)
  125. def enum(type, name, value):
  126. if not enums.has_key(type):
  127. enums[type] = {}
  128. enums[type][name] = value
  129. #######################################################################
  130. #
  131. # Some filtering rukes to drop functions/types which should not
  132. # be exposed as-is on the Python interface
  133. #
  134. #######################################################################
  135. skipped_modules = {
  136. 'xmlmemory': None,
  137. 'DOCBparser': None,
  138. 'SAX': None,
  139. 'hash': None,
  140. 'list': None,
  141. 'threads': None,
  142. # 'xpointer': None,
  143. }
  144. skipped_types = {
  145. 'int *': "usually a return type",
  146. 'xmlSAXHandlerPtr': "not the proper interface for SAX",
  147. 'htmlSAXHandlerPtr': "not the proper interface for SAX",
  148. 'xmlRMutexPtr': "thread specific, skipped",
  149. 'xmlMutexPtr': "thread specific, skipped",
  150. 'xmlGlobalStatePtr': "thread specific, skipped",
  151. 'xmlListPtr': "internal representation not suitable for python",
  152. 'xmlBufferPtr': "internal representation not suitable for python",
  153. 'FILE *': None,
  154. }
  155. #######################################################################
  156. #
  157. # Table of remapping to/from the python type or class to the C
  158. # counterpart.
  159. #
  160. #######################################################################
  161. py_types = {
  162. 'void': (None, None, None, None),
  163. 'int': ('i', None, "int", "int"),
  164. 'long': ('l', None, "long", "long"),
  165. 'double': ('d', None, "double", "double"),
  166. 'unsigned int': ('i', None, "int", "int"),
  167. 'xmlChar': ('c', None, "int", "int"),
  168. 'unsigned char *': ('z', None, "charPtr", "char *"),
  169. 'char *': ('z', None, "charPtr", "char *"),
  170. 'const char *': ('z', None, "charPtrConst", "const char *"),
  171. 'xmlChar *': ('z', None, "xmlCharPtr", "xmlChar *"),
  172. 'const xmlChar *': ('z', None, "xmlCharPtrConst", "const xmlChar *"),
  173. 'xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  174. 'const xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  175. 'xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  176. 'const xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  177. 'xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  178. 'const xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  179. 'xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  180. 'const xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  181. 'xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  182. 'const xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  183. 'xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  184. 'const xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  185. 'xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  186. 'const xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  187. 'xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  188. 'const xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  189. 'xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
  190. 'const xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
  191. 'xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
  192. 'const xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
  193. 'xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
  194. 'const xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
  195. 'xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
  196. 'const xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
  197. 'xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
  198. 'const xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
  199. 'xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
  200. 'const xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
  201. 'xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  202. 'const xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  203. 'xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  204. 'const xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  205. 'htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  206. 'const htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  207. 'htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  208. 'const htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
  209. 'htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  210. 'const htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  211. 'htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  212. 'const htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
  213. 'xmlXPathContextPtr': ('O', "xmlXPathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"),
  214. 'xmlXPathContext *': ('O', "xpathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"),
  215. 'xmlXPathParserContextPtr': ('O', "xmlXPathParserContext", "xmlXPathParserContextPtr", "xmlXPathParserContextPtr"),
  216. 'xmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
  217. 'xmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
  218. 'htmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
  219. 'htmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
  220. 'xmlValidCtxtPtr': ('O', "ValidCtxt", "xmlValidCtxtPtr", "xmlValidCtxtPtr"),
  221. 'xmlCatalogPtr': ('O', "catalog", "xmlCatalogPtr", "xmlCatalogPtr"),
  222. 'FILE *': ('O', "File", "FILEPtr", "FILE *"),
  223. 'xmlURIPtr': ('O', "URI", "xmlURIPtr", "xmlURIPtr"),
  224. 'xmlErrorPtr': ('O', "Error", "xmlErrorPtr", "xmlErrorPtr"),
  225. 'xmlOutputBufferPtr': ('O', "outputBuffer", "xmlOutputBufferPtr", "xmlOutputBufferPtr"),
  226. 'xmlParserInputBufferPtr': ('O', "inputBuffer", "xmlParserInputBufferPtr", "xmlParserInputBufferPtr"),
  227. 'xmlRegexpPtr': ('O', "xmlReg", "xmlRegexpPtr", "xmlRegexpPtr"),
  228. 'xmlTextReaderLocatorPtr': ('O', "xmlTextReaderLocator", "xmlTextReaderLocatorPtr", "xmlTextReaderLocatorPtr"),
  229. 'xmlTextReaderPtr': ('O', "xmlTextReader", "xmlTextReaderPtr", "xmlTextReaderPtr"),
  230. 'xmlRelaxNGPtr': ('O', "relaxNgSchema", "xmlRelaxNGPtr", "xmlRelaxNGPtr"),
  231. 'xmlRelaxNGParserCtxtPtr': ('O', "relaxNgParserCtxt", "xmlRelaxNGParserCtxtPtr", "xmlRelaxNGParserCtxtPtr"),
  232. 'xmlRelaxNGValidCtxtPtr': ('O', "relaxNgValidCtxt", "xmlRelaxNGValidCtxtPtr", "xmlRelaxNGValidCtxtPtr"),
  233. 'xmlSchemaPtr': ('O', "Schema", "xmlSchemaPtr", "xmlSchemaPtr"),
  234. 'xmlSchemaParserCtxtPtr': ('O', "SchemaParserCtxt", "xmlSchemaParserCtxtPtr", "xmlSchemaParserCtxtPtr"),
  235. 'xmlSchemaValidCtxtPtr': ('O', "SchemaValidCtxt", "xmlSchemaValidCtxtPtr", "xmlSchemaValidCtxtPtr"),
  236. }
  237. py_return_types = {
  238. 'xmlXPathObjectPtr': ('O', "foo", "xmlXPathObjectPtr", "xmlXPathObjectPtr"),
  239. }
  240. unknown_types = {}
  241. foreign_encoding_args = (
  242. 'htmlCreateMemoryParserCtxt',
  243. 'htmlCtxtReadMemory',
  244. 'htmlParseChunk',
  245. 'htmlReadMemory',
  246. 'xmlCreateMemoryParserCtxt',
  247. 'xmlCtxtReadMemory',
  248. 'xmlCtxtResetPush',
  249. 'xmlParseChunk',
  250. 'xmlParseMemory',
  251. 'xmlReadMemory',
  252. 'xmlRecoverMemory',
  253. )
  254. #######################################################################
  255. #
  256. # This part writes the C <-> Python stubs libxml2-py.[ch] and
  257. # the table libxml2-export.c to add when registrering the Python module
  258. #
  259. #######################################################################
  260. # Class methods which are written by hand in libxml.c but the Python-level
  261. # code is still automatically generated (so they are not in skip_function()).
  262. skip_impl = (
  263. 'xmlSaveFileTo',
  264. 'xmlSaveFormatFileTo',
  265. )
  266. def skip_function(name):
  267. if name[0:12] == "xmlXPathWrap":
  268. return 1
  269. if name == "xmlFreeParserCtxt":
  270. return 1
  271. if name == "xmlCleanupParser":
  272. return 1
  273. if name == "xmlFreeTextReader":
  274. return 1
  275. # if name[0:11] == "xmlXPathNew":
  276. # return 1
  277. # the next function is defined in libxml.c
  278. if name == "xmlRelaxNGFreeValidCtxt":
  279. return 1
  280. if name == "xmlFreeValidCtxt":
  281. return 1
  282. if name == "xmlSchemaFreeValidCtxt":
  283. return 1
  284. #
  285. # Those are skipped because the Const version is used of the bindings
  286. # instead.
  287. #
  288. if name == "xmlTextReaderBaseUri":
  289. return 1
  290. if name == "xmlTextReaderLocalName":
  291. return 1
  292. if name == "xmlTextReaderName":
  293. return 1
  294. if name == "xmlTextReaderNamespaceUri":
  295. return 1
  296. if name == "xmlTextReaderPrefix":
  297. return 1
  298. if name == "xmlTextReaderXmlLang":
  299. return 1
  300. if name == "xmlTextReaderValue":
  301. return 1
  302. if name == "xmlOutputBufferClose": # handled by by the superclass
  303. return 1
  304. if name == "xmlOutputBufferFlush": # handled by by the superclass
  305. return 1
  306. if name == "xmlErrMemory":
  307. return 1
  308. if name == "xmlValidBuildContentModel":
  309. return 1
  310. if name == "xmlValidateElementDecl":
  311. return 1
  312. if name == "xmlValidateAttributeDecl":
  313. return 1
  314. return 0
  315. def print_function_wrapper(name, output, export, include):
  316. global py_types
  317. global unknown_types
  318. global functions
  319. global skipped_modules
  320. try:
  321. (desc, ret, args, file, cond) = functions[name]
  322. except:
  323. print "failed to get function %s infos"
  324. return
  325. if skipped_modules.has_key(file):
  326. return 0
  327. if skip_function(name) == 1:
  328. return 0
  329. if name in skip_impl:
  330. # Don't delete the function entry in the caller.
  331. return 1
  332. c_call = ""
  333. format=""
  334. format_args=""
  335. c_args=""
  336. c_return=""
  337. c_convert=""
  338. num_bufs=0
  339. for arg in args:
  340. # This should be correct
  341. if arg[1][0:6] == "const ":
  342. arg[1] = arg[1][6:]
  343. c_args = c_args + " %s %s;\n" % (arg[1], arg[0])
  344. if py_types.has_key(arg[1]):
  345. (f, t, n, c) = py_types[arg[1]]
  346. if (f == 'z') and (name in foreign_encoding_args) and (num_bufs == 0):
  347. f = 't#'
  348. if f != None:
  349. format = format + f
  350. if t != None:
  351. format_args = format_args + ", &pyobj_%s" % (arg[0])
  352. c_args = c_args + " PyObject *pyobj_%s;\n" % (arg[0])
  353. c_convert = c_convert + \
  354. " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0],
  355. arg[1], t, arg[0])
  356. else:
  357. format_args = format_args + ", &%s" % (arg[0])
  358. if f == 't#':
  359. format_args = format_args + ", &py_buffsize%d" % num_bufs
  360. c_args = c_args + " int py_buffsize%d;\n" % num_bufs
  361. num_bufs = num_bufs + 1
  362. if c_call != "":
  363. c_call = c_call + ", "
  364. c_call = c_call + "%s" % (arg[0])
  365. else:
  366. if skipped_types.has_key(arg[1]):
  367. return 0
  368. if unknown_types.has_key(arg[1]):
  369. lst = unknown_types[arg[1]]
  370. lst.append(name)
  371. else:
  372. unknown_types[arg[1]] = [name]
  373. return -1
  374. if format != "":
  375. format = format + ":%s" % (name)
  376. if ret[0] == 'void':
  377. if file == "python_accessor":
  378. if args[1][1] == "char *" or args[1][1] == "xmlChar *":
  379. c_call = "\n if (%s->%s != NULL) xmlFree(%s->%s);\n" % (
  380. args[0][0], args[1][0], args[0][0], args[1][0])
  381. c_call = c_call + " %s->%s = (%s)xmlStrdup((const xmlChar *)%s);\n" % (args[0][0],
  382. args[1][0], args[1][1], args[1][0])
  383. else:
  384. c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0],
  385. args[1][0])
  386. else:
  387. c_call = "\n %s(%s);\n" % (name, c_call)
  388. ret_convert = " Py_INCREF(Py_None);\n return(Py_None);\n"
  389. elif py_types.has_key(ret[0]):
  390. (f, t, n, c) = py_types[ret[0]]
  391. c_return = " %s c_retval;\n" % (ret[0])
  392. if file == "python_accessor" and ret[2] != None:
  393. c_call = "\n c_retval = %s->%s;\n" % (args[0][0], ret[2])
  394. else:
  395. c_call = "\n c_retval = %s(%s);\n" % (name, c_call)
  396. ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c)
  397. ret_convert = ret_convert + " return(py_retval);\n"
  398. elif py_return_types.has_key(ret[0]):
  399. (f, t, n, c) = py_return_types[ret[0]]
  400. c_return = " %s c_retval;\n" % (ret[0])
  401. c_call = "\n c_retval = %s(%s);\n" % (name, c_call)
  402. ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c)
  403. ret_convert = ret_convert + " return(py_retval);\n"
  404. else:
  405. if skipped_types.has_key(ret[0]):
  406. return 0
  407. if unknown_types.has_key(ret[0]):
  408. lst = unknown_types[ret[0]]
  409. lst.append(name)
  410. else:
  411. unknown_types[ret[0]] = [name]
  412. return -1
  413. if cond != None and cond != "":
  414. include.write("#if %s\n" % cond)
  415. export.write("#if %s\n" % cond)
  416. output.write("#if %s\n" % cond)
  417. include.write("PyObject * ")
  418. include.write("libxml_%s(PyObject *self, PyObject *args);\n" % (name))
  419. export.write(" { (char *)\"%s\", libxml_%s, METH_VARARGS, NULL },\n" %
  420. (name, name))
  421. if file == "python":
  422. # Those have been manually generated
  423. if cond != None and cond != "":
  424. include.write("#endif\n")
  425. export.write("#endif\n")
  426. output.write("#endif\n")
  427. return 1
  428. if file == "python_accessor" and ret[0] != "void" and ret[2] is None:
  429. # Those have been manually generated
  430. if cond != None and cond != "":
  431. include.write("#endif\n")
  432. export.write("#endif\n")
  433. output.write("#endif\n")
  434. return 1
  435. output.write("PyObject *\n")
  436. output.write("libxml_%s(PyObject *self ATTRIBUTE_UNUSED," % (name))
  437. output.write(" PyObject *args")
  438. if format == "":
  439. output.write(" ATTRIBUTE_UNUSED")
  440. output.write(") {\n")
  441. if ret[0] != 'void':
  442. output.write(" PyObject *py_retval;\n")
  443. if c_return != "":
  444. output.write(c_return)
  445. if c_args != "":
  446. output.write(c_args)
  447. if format != "":
  448. output.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
  449. (format, format_args))
  450. output.write(" return(NULL);\n")
  451. if c_convert != "":
  452. output.write(c_convert)
  453. output.write(c_call)
  454. output.write(ret_convert)
  455. output.write("}\n\n")
  456. if cond != None and cond != "":
  457. include.write("#endif /* %s */\n" % cond)
  458. export.write("#endif /* %s */\n" % cond)
  459. output.write("#endif /* %s */\n" % cond)
  460. return 1
  461. def buildStubs():
  462. global py_types
  463. global py_return_types
  464. global unknown_types
  465. try:
  466. f = open(os.path.join(srcPref,"libxml2-api.xml"))
  467. data = f.read()
  468. (parser, target) = getparser()
  469. parser.feed(data)
  470. parser.close()
  471. except IOError, msg:
  472. try:
  473. f = open(os.path.join(srcPref,"..","doc","libxml2-api.xml"))
  474. data = f.read()
  475. (parser, target) = getparser()
  476. parser.feed(data)
  477. parser.close()
  478. except IOError, msg:
  479. print file, ":", msg
  480. sys.exit(1)
  481. n = len(functions.keys())
  482. print "Found %d functions in libxml2-api.xml" % (n)
  483. py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
  484. try:
  485. f = open(os.path.join(srcPref,"libxml2-python-api.xml"))
  486. data = f.read()
  487. (parser, target) = getparser()
  488. parser.feed(data)
  489. parser.close()
  490. except IOError, msg:
  491. print file, ":", msg
  492. print "Found %d functions in libxml2-python-api.xml" % (
  493. len(functions.keys()) - n)
  494. nb_wrap = 0
  495. failed = 0
  496. skipped = 0
  497. include = open("libxml2-py.h", "w")
  498. include.write("/* Generated */\n\n")
  499. export = open("libxml2-export.c", "w")
  500. export.write("/* Generated */\n\n")
  501. wrapper = open("libxml2-py.c", "w")
  502. wrapper.write("/* Generated */\n\n")
  503. wrapper.write("#include <Python.h>\n")
  504. wrapper.write("#include <libxml/xmlversion.h>\n")
  505. wrapper.write("#include <libxml/tree.h>\n")
  506. wrapper.write("#include <libxml/xmlschemastypes.h>\n")
  507. wrapper.write("#include \"libxml_wrap.h\"\n")
  508. wrapper.write("#include \"libxml2-py.h\"\n\n")
  509. for function in functions.keys():
  510. ret = print_function_wrapper(function, wrapper, export, include)
  511. if ret < 0:
  512. failed = failed + 1
  513. del functions[function]
  514. if ret == 0:
  515. skipped = skipped + 1
  516. del functions[function]
  517. if ret == 1:
  518. nb_wrap = nb_wrap + 1
  519. include.close()
  520. export.close()
  521. wrapper.close()
  522. print "Generated %d wrapper functions, %d failed, %d skipped\n" % (nb_wrap,
  523. failed, skipped)
  524. print "Missing type converters: "
  525. for type in unknown_types.keys():
  526. print "%s:%d " % (type, len(unknown_types[type])),
  527. print
  528. #######################################################################
  529. #
  530. # This part writes part of the Python front-end classes based on
  531. # mapping rules between types and classes and also based on function
  532. # renaming to get consistent function names at the Python level
  533. #
  534. #######################################################################
  535. #
  536. # The type automatically remapped to generated classes
  537. #
  538. classes_type = {
  539. "xmlNodePtr": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
  540. "xmlNode *": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
  541. "xmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
  542. "xmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
  543. "htmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
  544. "htmlxmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
  545. "xmlAttrPtr": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
  546. "xmlAttr *": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
  547. "xmlNsPtr": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
  548. "xmlNs *": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
  549. "xmlDtdPtr": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
  550. "xmlDtd *": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
  551. "xmlEntityPtr": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
  552. "xmlEntity *": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
  553. "xmlElementPtr": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
  554. "xmlElement *": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
  555. "xmlAttributePtr": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
  556. "xmlAttribute *": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
  557. "xmlXPathContextPtr": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
  558. "xmlXPathContext *": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
  559. "xmlXPathParserContext *": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
  560. "xmlXPathParserContextPtr": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
  561. "xmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
  562. "xmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
  563. "htmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
  564. "htmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
  565. "xmlValidCtxtPtr": ("._o", "ValidCtxt(_obj=%s)", "ValidCtxt"),
  566. "xmlCatalogPtr": ("._o", "catalog(_obj=%s)", "catalog"),
  567. "xmlURIPtr": ("._o", "URI(_obj=%s)", "URI"),
  568. "xmlErrorPtr": ("._o", "Error(_obj=%s)", "Error"),
  569. "xmlOutputBufferPtr": ("._o", "outputBuffer(_obj=%s)", "outputBuffer"),
  570. "xmlParserInputBufferPtr": ("._o", "inputBuffer(_obj=%s)", "inputBuffer"),
  571. "xmlRegexpPtr": ("._o", "xmlReg(_obj=%s)", "xmlReg"),
  572. "xmlTextReaderLocatorPtr": ("._o", "xmlTextReaderLocator(_obj=%s)", "xmlTextReaderLocator"),
  573. "xmlTextReaderPtr": ("._o", "xmlTextReader(_obj=%s)", "xmlTextReader"),
  574. 'xmlRelaxNGPtr': ('._o', "relaxNgSchema(_obj=%s)", "relaxNgSchema"),
  575. 'xmlRelaxNGParserCtxtPtr': ('._o', "relaxNgParserCtxt(_obj=%s)", "relaxNgParserCtxt"),
  576. 'xmlRelaxNGValidCtxtPtr': ('._o', "relaxNgValidCtxt(_obj=%s)", "relaxNgValidCtxt"),
  577. 'xmlSchemaPtr': ("._o", "Schema(_obj=%s)", "Schema"),
  578. 'xmlSchemaParserCtxtPtr': ("._o", "SchemaParserCtxt(_obj=%s)", "SchemaParserCtxt"),
  579. 'xmlSchemaValidCtxtPtr': ("._o", "SchemaValidCtxt(_obj=%s)", "SchemaValidCtxt"),
  580. }
  581. converter_type = {
  582. "xmlXPathObjectPtr": "xpathObjectRet(%s)",
  583. }
  584. primary_classes = ["xmlNode", "xmlDoc"]
  585. classes_ancestor = {
  586. "xmlNode" : "xmlCore",
  587. "xmlDtd" : "xmlNode",
  588. "xmlDoc" : "xmlNode",
  589. "xmlAttr" : "xmlNode",
  590. "xmlNs" : "xmlNode",
  591. "xmlEntity" : "xmlNode",
  592. "xmlElement" : "xmlNode",
  593. "xmlAttribute" : "xmlNode",
  594. "outputBuffer": "ioWriteWrapper",
  595. "inputBuffer": "ioReadWrapper",
  596. "parserCtxt": "parserCtxtCore",
  597. "xmlTextReader": "xmlTextReaderCore",
  598. "ValidCtxt": "ValidCtxtCore",
  599. "SchemaValidCtxt": "SchemaValidCtxtCore",
  600. "relaxNgValidCtxt": "relaxNgValidCtxtCore",
  601. }
  602. classes_destructors = {
  603. "parserCtxt": "xmlFreeParserCtxt",
  604. "catalog": "xmlFreeCatalog",
  605. "URI": "xmlFreeURI",
  606. # "outputBuffer": "xmlOutputBufferClose",
  607. "inputBuffer": "xmlFreeParserInputBuffer",
  608. "xmlReg": "xmlRegFreeRegexp",
  609. "xmlTextReader": "xmlFreeTextReader",
  610. "relaxNgSchema": "xmlRelaxNGFree",
  611. "relaxNgParserCtxt": "xmlRelaxNGFreeParserCtxt",
  612. "relaxNgValidCtxt": "xmlRelaxNGFreeValidCtxt",
  613. "Schema": "xmlSchemaFree",
  614. "SchemaParserCtxt": "xmlSchemaFreeParserCtxt",
  615. "SchemaValidCtxt": "xmlSchemaFreeValidCtxt",
  616. "ValidCtxt": "xmlFreeValidCtxt",
  617. }
  618. functions_noexcept = {
  619. "xmlHasProp": 1,
  620. "xmlHasNsProp": 1,
  621. "xmlDocSetRootElement": 1,
  622. "xmlNodeGetNs": 1,
  623. "xmlNodeGetNsDefs": 1,
  624. "xmlNextElementSibling": 1,
  625. "xmlPreviousElementSibling": 1,
  626. "xmlFirstElementChild": 1,
  627. "xmlLastElementChild": 1,
  628. }
  629. reference_keepers = {
  630. "xmlTextReader": [('inputBuffer', 'input')],
  631. "relaxNgValidCtxt": [('relaxNgSchema', 'schema')],
  632. "SchemaValidCtxt": [('Schema', 'schema')],
  633. }
  634. function_classes = {}
  635. function_classes["None"] = []
  636. def nameFixup(name, classe, type, file):
  637. listname = classe + "List"
  638. ll = len(listname)
  639. l = len(classe)
  640. if name[0:l] == listname:
  641. func = name[l:]
  642. func = string.lower(func[0:1]) + func[1:]
  643. elif name[0:12] == "xmlParserGet" and file == "python_accessor":
  644. func = name[12:]
  645. func = string.lower(func[0:1]) + func[1:]
  646. elif name[0:12] == "xmlParserSet" and file == "python_accessor":
  647. func = name[12:]
  648. func = string.lower(func[0:1]) + func[1:]
  649. elif name[0:10] == "xmlNodeGet" and file == "python_accessor":
  650. func = name[10:]
  651. func = string.lower(func[0:1]) + func[1:]
  652. elif name[0:9] == "xmlURIGet" and file == "python_accessor":
  653. func = name[9:]
  654. func = string.lower(func[0:1]) + func[1:]
  655. elif name[0:9] == "xmlURISet" and file == "python_accessor":
  656. func = name[6:]
  657. func = string.lower(func[0:1]) + func[1:]
  658. elif name[0:11] == "xmlErrorGet" and file == "python_accessor":
  659. func = name[11:]
  660. func = string.lower(func[0:1]) + func[1:]
  661. elif name[0:17] == "xmlXPathParserGet" and file == "python_accessor":
  662. func = name[17:]
  663. func = string.lower(func[0:1]) + func[1:]
  664. elif name[0:11] == "xmlXPathGet" and file == "python_accessor":
  665. func = name[11:]
  666. func = string.lower(func[0:1]) + func[1:]
  667. elif name[0:11] == "xmlXPathSet" and file == "python_accessor":
  668. func = name[8:]
  669. func = string.lower(func[0:1]) + func[1:]
  670. elif name[0:15] == "xmlOutputBuffer" and file != "python":
  671. func = name[15:]
  672. func = string.lower(func[0:1]) + func[1:]
  673. elif name[0:20] == "xmlParserInputBuffer" and file != "python":
  674. func = name[20:]
  675. func = string.lower(func[0:1]) + func[1:]
  676. elif name[0:9] == "xmlRegexp" and file == "xmlregexp":
  677. func = "regexp" + name[9:]
  678. elif name[0:6] == "xmlReg" and file == "xmlregexp":
  679. func = "regexp" + name[6:]
  680. elif name[0:20] == "xmlTextReaderLocator" and file == "xmlreader":
  681. func = name[20:]
  682. elif name[0:18] == "xmlTextReaderConst" and file == "xmlreader":
  683. func = name[18:]
  684. elif name[0:13] == "xmlTextReader" and file == "xmlreader":
  685. func = name[13:]
  686. elif name[0:12] == "xmlReaderNew" and file == "xmlreader":
  687. func = name[9:]
  688. elif name[0:11] == "xmlACatalog":
  689. func = name[11:]
  690. func = string.lower(func[0:1]) + func[1:]
  691. elif name[0:l] == classe:
  692. func = name[l:]
  693. func = string.lower(func[0:1]) + func[1:]
  694. elif name[0:7] == "libxml_":
  695. func = name[7:]
  696. func = string.lower(func[0:1]) + func[1:]
  697. elif name[0:6] == "xmlGet":
  698. func = name[6:]
  699. func = string.lower(func[0:1]) + func[1:]
  700. elif name[0:3] == "xml":
  701. func = name[3:]
  702. func = string.lower(func[0:1]) + func[1:]
  703. else:
  704. func = name
  705. if func[0:5] == "xPath":
  706. func = "xpath" + func[5:]
  707. elif func[0:4] == "xPtr":
  708. func = "xpointer" + func[4:]
  709. elif func[0:8] == "xInclude":
  710. func = "xinclude" + func[8:]
  711. elif func[0:2] == "iD":
  712. func = "ID" + func[2:]
  713. elif func[0:3] == "uRI":
  714. func = "URI" + func[3:]
  715. elif func[0:4] == "uTF8":
  716. func = "UTF8" + func[4:]
  717. elif func[0:3] == 'sAX':
  718. func = "SAX" + func[3:]
  719. return func
  720. def functionCompare(info1, info2):
  721. (index1, func1, name1, ret1, args1, file1) = info1
  722. (index2, func2, name2, ret2, args2, file2) = info2
  723. if file1 == file2:
  724. if func1 < func2:
  725. return -1
  726. if func1 > func2:
  727. return 1
  728. if file1 == "python_accessor":
  729. return -1
  730. if file2 == "python_accessor":
  731. return 1
  732. if file1 < file2:
  733. return -1
  734. if file1 > file2:
  735. return 1
  736. return 0
  737. def writeDoc(name, args, indent, output):
  738. if functions[name][0] is None or functions[name][0] == "":
  739. return
  740. val = functions[name][0]
  741. val = string.replace(val, "NULL", "None")
  742. output.write(indent)
  743. output.write('"""')
  744. while len(val) > 60:
  745. if val[0] == " ":
  746. val = val[1:]
  747. continue
  748. str = val[0:60]
  749. i = string.rfind(str, " ")
  750. if i < 0:
  751. i = 60
  752. str = val[0:i]
  753. val = val[i:]
  754. output.write(str)
  755. output.write('\n ')
  756. output.write(indent)
  757. output.write(val)
  758. output.write(' """\n')
  759. def buildWrappers():
  760. global ctypes
  761. global py_types
  762. global py_return_types
  763. global unknown_types
  764. global functions
  765. global function_classes
  766. global classes_type
  767. global classes_list
  768. global converter_type
  769. global primary_classes
  770. global converter_type
  771. global classes_ancestor
  772. global converter_type
  773. global primary_classes
  774. global classes_ancestor
  775. global classes_destructors
  776. global functions_noexcept
  777. for type in classes_type.keys():
  778. function_classes[classes_type[type][2]] = []
  779. #
  780. # Build the list of C types to look for ordered to start
  781. # with primary classes
  782. #
  783. ctypes = []
  784. classes_list = []
  785. ctypes_processed = {}
  786. classes_processed = {}
  787. for classe in primary_classes:
  788. classes_list.append(classe)
  789. classes_processed[classe] = ()
  790. for type in classes_type.keys():
  791. tinfo = classes_type[type]
  792. if tinfo[2] == classe:
  793. ctypes.append(type)
  794. ctypes_processed[type] = ()
  795. for type in classes_type.keys():
  796. if ctypes_processed.has_key(type):
  797. continue
  798. tinfo = classes_type[type]
  799. if not classes_processed.has_key(tinfo[2]):
  800. classes_list.append(tinfo[2])
  801. classes_processed[tinfo[2]] = ()
  802. ctypes.append(type)
  803. ctypes_processed[type] = ()
  804. for name in functions.keys():
  805. found = 0
  806. (desc, ret, args, file, cond) = functions[name]
  807. for type in ctypes:
  808. classe = classes_type[type][2]
  809. if name[0:3] == "xml" and len(args) >= 1 and args[0][1] == type:
  810. found = 1
  811. func = nameFixup(name, classe, type, file)
  812. info = (0, func, name, ret, args, file)
  813. function_classes[classe].append(info)
  814. elif name[0:3] == "xml" and len(args) >= 2 and args[1][1] == type \
  815. and file != "python_accessor":
  816. found = 1
  817. func = nameFixup(name, classe, type, file)
  818. info = (1, func, name, ret, args, file)
  819. function_classes[classe].append(info)
  820. elif name[0:4] == "html" and len(args) >= 1 and args[0][1] == type:
  821. found = 1
  822. func = nameFixup(name, classe, type, file)
  823. info = (0, func, name, ret, args, file)
  824. function_classes[classe].append(info)
  825. elif name[0:4] == "html" and len(args) >= 2 and args[1][1] == type \
  826. and file != "python_accessor":
  827. found = 1
  828. func = nameFixup(name, classe, type, file)
  829. info = (1, func, name, ret, args, file)
  830. function_classes[classe].append(info)
  831. if found == 1:
  832. continue
  833. if name[0:8] == "xmlXPath":
  834. continue
  835. if name[0:6] == "xmlStr":
  836. continue
  837. if name[0:10] == "xmlCharStr":
  838. continue
  839. func = nameFixup(name, "None", file, file)
  840. info = (0, func, name, ret, args, file)
  841. function_classes['None'].append(info)
  842. classes = open("libxml2class.py", "w")
  843. txt = open("libxml2class.txt", "w")
  844. txt.write(" Generated Classes for libxml2-python\n\n")
  845. txt.write("#\n# Global functions of the module\n#\n\n")
  846. if function_classes.has_key("None"):
  847. flist = function_classes["None"]
  848. flist.sort(functionCompare)
  849. oldfile = ""
  850. for info in flist:
  851. (index, func, name, ret, args, file) = info
  852. if file != oldfile:
  853. classes.write("#\n# Functions from module %s\n#\n\n" % file)
  854. txt.write("\n# functions from module %s\n" % file)
  855. oldfile = file
  856. classes.write("def %s(" % func)
  857. txt.write("%s()\n" % func)
  858. n = 0
  859. for arg in args:
  860. if n != 0:
  861. classes.write(", ")
  862. classes.write("%s" % arg[0])
  863. n = n + 1
  864. classes.write("):\n")
  865. writeDoc(name, args, ' ', classes)
  866. for arg in args:
  867. if classes_type.has_key(arg[1]):
  868. classes.write(" if %s is None: %s__o = None\n" %
  869. (arg[0], arg[0]))
  870. classes.write(" else: %s__o = %s%s\n" %
  871. (arg[0], arg[0], classes_type[arg[1]][0]))
  872. if ret[0] != "void":
  873. classes.write(" ret = ")
  874. else:
  875. classes.write(" ")
  876. classes.write("libxml2mod.%s(" % name)
  877. n = 0
  878. for arg in args:
  879. if n != 0:
  880. classes.write(", ")
  881. classes.write("%s" % arg[0])
  882. if classes_type.has_key(arg[1]):
  883. classes.write("__o")
  884. n = n + 1
  885. classes.write(")\n")
  886. if ret[0] != "void":
  887. if classes_type.has_key(ret[0]):
  888. #
  889. # Raise an exception
  890. #
  891. if functions_noexcept.has_key(name):
  892. classes.write(" if ret is None:return None\n")
  893. elif string.find(name, "URI") >= 0:
  894. classes.write(
  895. " if ret is None:raise uriError('%s() failed')\n"
  896. % (name))
  897. elif string.find(name, "XPath") >= 0:
  898. classes.write(
  899. " if ret is None:raise xpathError('%s() failed')\n"
  900. % (name))
  901. elif string.find(name, "Parse") >= 0:
  902. classes.write(
  903. " if ret is None:raise parserError('%s() failed')\n"
  904. % (name))
  905. else:
  906. classes.write(
  907. " if ret is None:raise treeError('%s() failed')\n"
  908. % (name))
  909. classes.write(" return ")
  910. classes.write(classes_type[ret[0]][1] % ("ret"))
  911. classes.write("\n")
  912. else:
  913. classes.write(" return ret\n")
  914. classes.write("\n")
  915. txt.write("\n\n#\n# Set of classes of the module\n#\n\n")
  916. for classname in classes_list:
  917. if classname == "None":
  918. pass
  919. else:
  920. if classes_ancestor.has_key(classname):
  921. txt.write("\n\nClass %s(%s)\n" % (classname,
  922. classes_ancestor[classname]))
  923. classes.write("class %s(%s):\n" % (classname,
  924. classes_ancestor[classname]))
  925. classes.write(" def __init__(self, _obj=None):\n")
  926. if classes_ancestor[classname] == "xmlCore" or \
  927. classes_ancestor[classname] == "xmlNode":
  928. classes.write(" if type(_obj).__name__ != ")
  929. classes.write("'PyCObject':\n")
  930. classes.write(" raise TypeError, ")
  931. classes.write("'%s needs a PyCObject argument'\n" % \
  932. classname)
  933. if reference_keepers.has_key(classname):
  934. rlist = reference_keepers[classname]
  935. for ref in rlist:
  936. classes.write(" self.%s = None\n" % ref[1])
  937. classes.write(" self._o = _obj\n")
  938. classes.write(" %s.__init__(self, _obj=_obj)\n\n" % (
  939. classes_ancestor[classname]))
  940. if classes_ancestor[classname] == "xmlCore" or \
  941. classes_ancestor[classname] == "xmlNode":
  942. classes.write(" def __repr__(self):\n")
  943. format = "<%s (%%s) object at 0x%%x>" % (classname)
  944. classes.write(" return \"%s\" %% (self.name, long(pos_id (self)))\n\n" % (
  945. format))
  946. else:
  947. txt.write("Class %s()\n" % (classname))
  948. classes.write("class %s:\n" % (classname))
  949. classes.write(" def __init__(self, _obj=None):\n")
  950. if reference_keepers.has_key(classname):
  951. list = reference_keepers[classname]
  952. for ref in list:
  953. classes.write(" self.%s = None\n" % ref[1])
  954. classes.write(" if _obj != None:self._o = _obj;return\n")
  955. classes.write(" self._o = None\n\n")
  956. destruct=None
  957. if classes_destructors.has_key(classname):
  958. classes.write(" def __del__(self):\n")
  959. classes.write(" if self._o != None:\n")
  960. classes.write(" libxml2mod.%s(self._o)\n" %
  961. classes_destructors[classname])
  962. classes.write(" self._o = None\n\n")
  963. destruct=classes_destructors[classname]
  964. flist = function_classes[classname]
  965. flist.sort(functionCompare)
  966. oldfile = ""
  967. for info in flist:
  968. (index, func, name, ret, args, file) = info
  969. #
  970. # Do not provide as method the destructors for the class
  971. # to avoid double free
  972. #
  973. if name == destruct:
  974. continue
  975. if file != oldfile:
  976. if file == "python_accessor":
  977. classes.write(" # accessors for %s\n" % (classname))
  978. txt.write(" # accessors\n")
  979. else:
  980. classes.write(" #\n")
  981. classes.write(" # %s functions from module %s\n" % (
  982. classname, file))
  983. txt.write("\n # functions from module %s\n" % file)
  984. classes.write(" #\n\n")
  985. oldfile = file
  986. classes.write(" def %s(self" % func)
  987. txt.write(" %s()\n" % func)
  988. n = 0
  989. for arg in args:
  990. if n != index:
  991. classes.write(", %s" % arg[0])
  992. n = n + 1
  993. classes.write("):\n")
  994. writeDoc(name, args, ' ', classes)
  995. n = 0
  996. for arg in args:
  997. if classes_type.has_key(arg[1]):
  998. if n != index:
  999. classes.write(" if %s is None: %s__o = None\n" %
  1000. (arg[0], arg[0]))
  1001. classes.write(" else: %s__o = %s%s\n" %
  1002. (arg[0], arg[0], classes_type[arg[1]][0]))
  1003. n = n + 1
  1004. if ret[0] != "void":
  1005. classes.write(" ret = ")
  1006. else:
  1007. classes.write(" ")
  1008. classes.write("libxml2mod.%s(" % name)
  1009. n = 0
  1010. for arg in args:
  1011. if n != 0:
  1012. classes.write(", ")
  1013. if n != index:
  1014. classes.write("%s" % arg[0])
  1015. if classes_type.has_key(arg[1]):
  1016. classes.write("__o")
  1017. else:
  1018. classes.write("self")
  1019. if classes_type.has_key(arg[1]):
  1020. classes.write(classes_type[arg[1]][0])
  1021. n = n + 1
  1022. classes.write(")\n")
  1023. if ret[0] != "void":
  1024. if classes_type.has_key(ret[0]):
  1025. #
  1026. # Raise an exception
  1027. #
  1028. if functions_noexcept.has_key(name):
  1029. classes.write(
  1030. " if ret is None:return None\n")
  1031. elif string.find(name, "URI") >= 0:
  1032. classes.write(
  1033. " if ret is None:raise uriError('%s() failed')\n"
  1034. % (name))
  1035. elif string.find(name, "XPath") >= 0:
  1036. classes.write(
  1037. " if ret is None:raise xpathError('%s() failed')\n"
  1038. % (name))
  1039. elif string.find(name, "Parse") >= 0:
  1040. classes.write(
  1041. " if ret is None:raise parserError('%s() failed')\n"
  1042. % (name))
  1043. else:
  1044. classes.write(
  1045. " if ret is None:raise treeError('%s() failed')\n"
  1046. % (name))
  1047. #
  1048. # generate the returned class wrapper for the object
  1049. #
  1050. classes.write(" __tmp = ")
  1051. classes.write(classes_type[ret[0]][1] % ("ret"))
  1052. classes.write("\n")
  1053. #
  1054. # Sometime one need to keep references of the source
  1055. # class in the returned class object.
  1056. # See reference_keepers for the list
  1057. #
  1058. tclass = classes_type[ret[0]][2]
  1059. if reference_keepers.has_key(tclass):
  1060. list = reference_keepers[tclass]
  1061. for pref in list:
  1062. if pref[0] == classname:
  1063. classes.write(" __tmp.%s = self\n" %
  1064. pref[1])
  1065. #
  1066. # return the class
  1067. #
  1068. classes.write(" return __tmp\n")
  1069. elif converter_type.has_key(ret[0]):
  1070. #
  1071. # Raise an exception
  1072. #
  1073. if functions_noexcept.has_key(name):
  1074. classes.write(
  1075. " if ret is None:return None")
  1076. elif string.find(name, "URI") >= 0:
  1077. classes.write(
  1078. " if ret is None:raise uriError('%s() failed')\n"
  1079. % (name))
  1080. elif string.find(name, "XPath") >= 0:
  1081. classes.write(
  1082. " if ret is None:raise xpathError('%s() failed')\n"
  1083. % (name))
  1084. elif string.find(name, "Parse") >= 0:
  1085. classes.write(
  1086. " if ret is None:raise parserError('%s() failed')\n"
  1087. % (name))
  1088. else:
  1089. classes.write(
  1090. " if ret is None:raise treeError('%s() failed')\n"
  1091. % (name))
  1092. classes.write(" return ")
  1093. classes.write(converter_type[ret[0]] % ("ret"))
  1094. classes.write("\n")
  1095. else:
  1096. classes.write(" return ret\n")
  1097. classes.write("\n")
  1098. #
  1099. # Generate enum constants
  1100. #
  1101. for type,enum in enums.items():
  1102. classes.write("# %s\n" % type)
  1103. items = enum.items()
  1104. items.sort(lambda i1,i2: cmp(long(i1[1]),long(i2[1])))
  1105. for name,value in items:
  1106. classes.write("%s = %s\n" % (name,value))
  1107. classes.write("\n")
  1108. txt.close()
  1109. classes.close()
  1110. buildStubs()
  1111. buildWrappers()