blob: 7a575c57601d0ac27e034dfc9c149ed13a280074 [file] [log] [blame]
Daniel Veillardd2897fd2002-01-30 16:37:32 +00001#!/usr/bin/python -u
2#
3# generate python wrappers from the XML API description
4#
5
6functions = {}
7
Daniel Veillard0fea6f42002-02-22 22:51:13 +00008import sys
Daniel Veillard36ed5292002-01-30 23:49:06 +00009import string
Daniel Veillard1971ee22002-01-31 20:29:19 +000010
11#######################################################################
12#
13# That part if purely the API acquisition phase from the
14# XML API description
15#
16#######################################################################
17import os
Daniel Veillardd2897fd2002-01-30 16:37:32 +000018import xmllib
19try:
20 import sgmlop
21except ImportError:
22 sgmlop = None # accelerator not available
23
24debug = 0
25
26if sgmlop:
27 class FastParser:
Daniel Veillard01a6d412002-02-11 18:42:20 +000028 """sgmlop based XML parser. this is typically 15x faster
29 than SlowParser..."""
Daniel Veillardd2897fd2002-01-30 16:37:32 +000030
Daniel Veillard01a6d412002-02-11 18:42:20 +000031 def __init__(self, target):
Daniel Veillardd2897fd2002-01-30 16:37:32 +000032
Daniel Veillard01a6d412002-02-11 18:42:20 +000033 # setup callbacks
34 self.finish_starttag = target.start
35 self.finish_endtag = target.end
36 self.handle_data = target.data
Daniel Veillardd2897fd2002-01-30 16:37:32 +000037
Daniel Veillard01a6d412002-02-11 18:42:20 +000038 # activate parser
39 self.parser = sgmlop.XMLParser()
40 self.parser.register(self)
41 self.feed = self.parser.feed
42 self.entity = {
43 "amp": "&", "gt": ">", "lt": "<",
44 "apos": "'", "quot": '"'
45 }
Daniel Veillardd2897fd2002-01-30 16:37:32 +000046
Daniel Veillard01a6d412002-02-11 18:42:20 +000047 def close(self):
48 try:
49 self.parser.close()
50 finally:
51 self.parser = self.feed = None # nuke circular reference
Daniel Veillardd2897fd2002-01-30 16:37:32 +000052
Daniel Veillard01a6d412002-02-11 18:42:20 +000053 def handle_entityref(self, entity):
54 # <string> entity
55 try:
56 self.handle_data(self.entity[entity])
57 except KeyError:
58 self.handle_data("&%s;" % entity)
Daniel Veillardd2897fd2002-01-30 16:37:32 +000059
60else:
61 FastParser = None
62
63
64class SlowParser(xmllib.XMLParser):
65 """slow but safe standard parser, based on the XML parser in
66 Python's standard library."""
67
68 def __init__(self, target):
Daniel Veillard01a6d412002-02-11 18:42:20 +000069 self.unknown_starttag = target.start
70 self.handle_data = target.data
71 self.unknown_endtag = target.end
72 xmllib.XMLParser.__init__(self)
Daniel Veillardd2897fd2002-01-30 16:37:32 +000073
74def getparser(target = None):
75 # get the fastest available parser, and attach it to an
76 # unmarshalling object. return both objects.
77 if target == None:
Daniel Veillard01a6d412002-02-11 18:42:20 +000078 target = docParser()
Daniel Veillardd2897fd2002-01-30 16:37:32 +000079 if FastParser:
Daniel Veillard01a6d412002-02-11 18:42:20 +000080 return FastParser(target), target
Daniel Veillardd2897fd2002-01-30 16:37:32 +000081 return SlowParser(target), target
82
83class docParser:
84 def __init__(self):
85 self._methodname = None
Daniel Veillard01a6d412002-02-11 18:42:20 +000086 self._data = []
87 self.in_function = 0
Daniel Veillardd2897fd2002-01-30 16:37:32 +000088
89 def close(self):
90 if debug:
Daniel Veillard01a6d412002-02-11 18:42:20 +000091 print "close"
Daniel Veillardd2897fd2002-01-30 16:37:32 +000092
93 def getmethodname(self):
94 return self._methodname
95
96 def data(self, text):
97 if debug:
Daniel Veillard01a6d412002-02-11 18:42:20 +000098 print "data %s" % text
Daniel Veillardd2897fd2002-01-30 16:37:32 +000099 self._data.append(text)
100
101 def start(self, tag, attrs):
102 if debug:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000103 print "start %s, %s" % (tag, attrs)
104 if tag == 'function':
105 self._data = []
106 self.in_function = 1
107 self.function = None
108 self.function_args = []
109 self.function_descr = None
110 self.function_return = None
111 self.function_file = None
112 if attrs.has_key('name'):
113 self.function = attrs['name']
114 if attrs.has_key('file'):
115 self.function_file = attrs['file']
116 elif tag == 'info':
117 self._data = []
118 elif tag == 'arg':
119 if self.in_function == 1:
120 self.function_arg_name = None
121 self.function_arg_type = None
122 self.function_arg_info = None
123 if attrs.has_key('name'):
124 self.function_arg_name = attrs['name']
125 if attrs.has_key('type'):
126 self.function_arg_type = attrs['type']
127 if attrs.has_key('info'):
128 self.function_arg_info = attrs['info']
129 elif tag == 'return':
130 if self.in_function == 1:
131 self.function_return_type = None
132 self.function_return_info = None
133 self.function_return_field = None
134 if attrs.has_key('type'):
135 self.function_return_type = attrs['type']
136 if attrs.has_key('info'):
137 self.function_return_info = attrs['info']
138 if attrs.has_key('field'):
139 self.function_return_field = attrs['field']
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000140
141
142 def end(self, tag):
143 if debug:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000144 print "end %s" % tag
145 if tag == 'function':
146 if self.function != None:
147 function(self.function, self.function_descr,
148 self.function_return, self.function_args,
149 self.function_file)
150 self.in_function = 0
151 elif tag == 'arg':
152 if self.in_function == 1:
153 self.function_args.append([self.function_arg_name,
154 self.function_arg_type,
155 self.function_arg_info])
156 elif tag == 'return':
157 if self.in_function == 1:
158 self.function_return = [self.function_return_type,
159 self.function_return_info,
160 self.function_return_field]
161 elif tag == 'info':
162 str = ''
163 for c in self._data:
164 str = str + c
165 if self.in_function == 1:
166 self.function_descr = str
167
168
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000169def function(name, desc, ret, args, file):
170 global functions
171
172 functions[name] = (desc, ret, args, file)
173
Daniel Veillard1971ee22002-01-31 20:29:19 +0000174#######################################################################
175#
176# Some filtering rukes to drop functions/types which should not
177# be exposed as-is on the Python interface
178#
179#######################################################################
Daniel Veillard36ed5292002-01-30 23:49:06 +0000180
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000181skipped_modules = {
182 'xmlmemory': None,
Daniel Veillard96fe0952002-01-30 20:52:23 +0000183 'DOCBparser': None,
184 'SAX': None,
185 'hash': None,
186 'list': None,
187 'threads': None,
Daniel Veillard1971ee22002-01-31 20:29:19 +0000188 'xpointer': None,
Daniel Veillard96fe0952002-01-30 20:52:23 +0000189}
190skipped_types = {
191 'int *': "usually a return type",
192 'xmlSAXHandlerPtr': "not the proper interface for SAX",
193 'htmlSAXHandlerPtr': "not the proper interface for SAX",
Daniel Veillard96fe0952002-01-30 20:52:23 +0000194 'xmlRMutexPtr': "thread specific, skipped",
195 'xmlMutexPtr': "thread specific, skipped",
196 'xmlGlobalStatePtr': "thread specific, skipped",
197 'xmlListPtr': "internal representation not suitable for python",
198 'xmlBufferPtr': "internal representation not suitable for python",
199 'FILE *': None,
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000200}
Daniel Veillard1971ee22002-01-31 20:29:19 +0000201
202#######################################################################
203#
204# Table of remapping to/from the python type or class to the C
205# counterpart.
206#
207#######################################################################
208
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000209py_types = {
Daniel Veillard96fe0952002-01-30 20:52:23 +0000210 'void': (None, None, None, None),
211 'int': ('i', None, "int", "int"),
212 'long': ('i', None, "int", "int"),
213 'double': ('d', None, "double", "double"),
214 'unsigned int': ('i', None, "int", "int"),
215 'xmlChar': ('c', None, "int", "int"),
Daniel Veillard253aa2c2002-02-02 09:17:16 +0000216 'unsigned char *': ('z', None, "charPtr", "char *"),
217 'char *': ('z', None, "charPtr", "char *"),
Daniel Veillardc575b992002-02-08 13:28:40 +0000218 'const char *': ('z', None, "charPtrConst", "const char *"),
Daniel Veillard253aa2c2002-02-02 09:17:16 +0000219 'xmlChar *': ('z', None, "xmlCharPtr", "xmlChar *"),
Daniel Veillardc575b992002-02-08 13:28:40 +0000220 'const xmlChar *': ('z', None, "xmlCharPtrConst", "const xmlChar *"),
Daniel Veillard96fe0952002-01-30 20:52:23 +0000221 'xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
222 'const xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
223 'xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
224 'const xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
225 'xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
226 'const xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
227 'xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
228 'const xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
229 'xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
230 'const xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
231 'xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
232 'const xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
233 'xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
234 'const xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
235 'xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
236 'const xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
Daniel Veillard1971ee22002-01-31 20:29:19 +0000237 'xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
238 'const xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
239 'xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
240 'const xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"),
241 'xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
242 'const xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
243 'xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
244 'const xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"),
245 'xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
246 'const xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
247 'xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
248 'const xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"),
Daniel Veillard96fe0952002-01-30 20:52:23 +0000249 'xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
250 'const xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
251 'xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
252 'const xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
253 'htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
254 'const htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
255 'htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
256 'const htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"),
257 'htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
258 'const htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
259 'htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
260 'const htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"),
Daniel Veillard1971ee22002-01-31 20:29:19 +0000261 'xmlXPathContextPtr': ('O', "xmlXPathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"),
262 'xmlXPathContext *': ('O', "xpathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"),
Daniel Veillard7db38712002-02-07 16:39:11 +0000263 'xmlXPathParserContextPtr': ('O', "xmlXPathParserContext", "xmlXPathParserContextPtr", "xmlXPathParserContextPtr"),
Daniel Veillard3ce52572002-02-03 15:08:05 +0000264 'xmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
265 'xmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
266 'htmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
267 'htmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"),
Daniel Veillard7db38712002-02-07 16:39:11 +0000268 'xmlCatalogPtr': ('O', "catalog", "xmlCatalogPtr", "xmlCatalogPtr"),
269 'FILE *': ('O', "File", "FILEPtr", "FILE *"),
Daniel Veillard1971ee22002-01-31 20:29:19 +0000270}
271
272py_return_types = {
273 'xmlXPathObjectPtr': ('O', "foo", "xmlXPathObjectPtr", "xmlXPathObjectPtr"),
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000274}
275
276unknown_types = {}
277
Daniel Veillard1971ee22002-01-31 20:29:19 +0000278#######################################################################
279#
280# This part writes the C <-> Python stubs libxml2-py.[ch] and
281# the table libxml2-export.c to add when registrering the Python module
282#
283#######################################################################
284
285def skip_function(name):
286 if name[0:12] == "xmlXPathWrap":
287 return 1
288# if name[0:11] == "xmlXPathNew":
289# return 1
290 return 0
291
Daniel Veillard96fe0952002-01-30 20:52:23 +0000292def print_function_wrapper(name, output, export, include):
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000293 global py_types
294 global unknown_types
295 global functions
296 global skipped_modules
297
298 try:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000299 (desc, ret, args, file) = functions[name]
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000300 except:
301 print "failed to get function %s infos"
302 return
303
304 if skipped_modules.has_key(file):
305 return 0
Daniel Veillard1971ee22002-01-31 20:29:19 +0000306 if skip_function(name) == 1:
307 return 0
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000308
309 c_call = "";
310 format=""
311 format_args=""
312 c_args=""
313 c_return=""
Daniel Veillard96fe0952002-01-30 20:52:23 +0000314 c_convert=""
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000315 for arg in args:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000316 # This should be correct
317 if arg[1][0:6] == "const ":
318 arg[1] = arg[1][6:]
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000319 c_args = c_args + " %s %s;\n" % (arg[1], arg[0])
Daniel Veillard01a6d412002-02-11 18:42:20 +0000320 if py_types.has_key(arg[1]):
321 (f, t, n, c) = py_types[arg[1]]
322 if f != None:
323 format = format + f
324 if t != None:
325 format_args = format_args + ", &pyobj_%s" % (arg[0])
326 c_args = c_args + " PyObject *pyobj_%s;\n" % (arg[0])
327 c_convert = c_convert + \
328 " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0],
329 arg[1], t, arg[0]);
330 else:
331 format_args = format_args + ", &%s" % (arg[0])
332 if c_call != "":
333 c_call = c_call + ", ";
334 c_call = c_call + "%s" % (arg[0])
335 else:
336 if skipped_types.has_key(arg[1]):
337 return 0
338 if unknown_types.has_key(arg[1]):
339 lst = unknown_types[arg[1]]
340 lst.append(name)
341 else:
342 unknown_types[arg[1]] = [name]
343 return -1
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000344 if format != "":
345 format = format + ":%s" % (name)
346
347 if ret[0] == 'void':
Daniel Veillard01a6d412002-02-11 18:42:20 +0000348 if file == "python_accessor":
349 c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0],
350 args[1][0])
351 else:
352 c_call = "\n %s(%s);\n" % (name, c_call);
353 ret_convert = " Py_INCREF(Py_None);\n return(Py_None);\n"
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000354 elif py_types.has_key(ret[0]):
Daniel Veillard01a6d412002-02-11 18:42:20 +0000355 (f, t, n, c) = py_types[ret[0]]
356 c_return = " %s c_retval;\n" % (ret[0])
357 if file == "python_accessor" and ret[2] != None:
358 c_call = "\n c_retval = %s->%s;\n" % (args[0][0], ret[2])
359 else:
360 c_call = "\n c_retval = %s(%s);\n" % (name, c_call);
361 ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c)
362 ret_convert = ret_convert + " return(py_retval);\n"
Daniel Veillard1971ee22002-01-31 20:29:19 +0000363 elif py_return_types.has_key(ret[0]):
Daniel Veillard01a6d412002-02-11 18:42:20 +0000364 (f, t, n, c) = py_return_types[ret[0]]
365 c_return = " %s c_retval;\n" % (ret[0])
Daniel Veillard1971ee22002-01-31 20:29:19 +0000366 c_call = "\n c_retval = %s(%s);\n" % (name, c_call);
Daniel Veillard01a6d412002-02-11 18:42:20 +0000367 ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c)
368 ret_convert = ret_convert + " return(py_retval);\n"
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000369 else:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000370 if skipped_types.has_key(ret[0]):
371 return 0
372 if unknown_types.has_key(ret[0]):
373 lst = unknown_types[ret[0]]
374 lst.append(name)
375 else:
376 unknown_types[ret[0]] = [name]
377 return -1
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000378
Daniel Veillard96fe0952002-01-30 20:52:23 +0000379 include.write("PyObject * ")
380 include.write("libxml_%s(PyObject *self, PyObject *args);\n" % (name))
Daniel Veillard9589d452002-02-02 10:28:17 +0000381
Daniel Veillard5e5c2d02002-02-09 18:03:01 +0000382 export.write(" { \"%s\", libxml_%s, METH_VARARGS, NULL },\n" %
383 (name, name))
Daniel Veillard9589d452002-02-02 10:28:17 +0000384
385 if file == "python":
386 # Those have been manually generated
Daniel Veillard01a6d412002-02-11 18:42:20 +0000387 return 1
Daniel Veillard36eea2d2002-02-04 00:17:01 +0000388 if file == "python_accessor" and ret[0] != "void" and ret[2] == None:
389 # Those have been manually generated
Daniel Veillard01a6d412002-02-11 18:42:20 +0000390 return 1
Daniel Veillard9589d452002-02-02 10:28:17 +0000391
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000392 output.write("PyObject *\n")
393 output.write("libxml_%s(PyObject *self, PyObject *args) {\n" % (name))
394 if ret[0] != 'void':
Daniel Veillard01a6d412002-02-11 18:42:20 +0000395 output.write(" PyObject *py_retval;\n")
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000396 if c_return != "":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000397 output.write(c_return)
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000398 if c_args != "":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000399 output.write(c_args)
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000400 if format != "":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000401 output.write("\n if (!PyArg_ParseTuple(args, \"%s\"%s))\n" %
402 (format, format_args))
403 output.write(" return(NULL);\n")
Daniel Veillard96fe0952002-01-30 20:52:23 +0000404 if c_convert != "":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000405 output.write(c_convert)
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000406
407 output.write(c_call)
408 output.write(ret_convert)
409 output.write("}\n\n")
410 return 1
411
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000412def buildStubs():
413 global py_types
414 global py_return_types
415 global unknown_types
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000416
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000417 try:
418 f = open("libxml2-api.xml")
419 data = f.read()
420 (parser, target) = getparser()
421 parser.feed(data)
422 parser.close()
423 except IOError, msg:
424 try:
425 f = open("../doc/libxml2-api.xml")
426 data = f.read()
427 (parser, target) = getparser()
428 parser.feed(data)
429 parser.close()
430 except IOError, msg:
431 print file, ":", msg
432 sys.exit(1)
Daniel Veillard9589d452002-02-02 10:28:17 +0000433
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000434 n = len(functions.keys())
435 print "Found %d functions in libxml2-api.xml" % (n)
436
437 py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
438 try:
439 f = open("libxml2-python-api.xml")
440 data = f.read()
441 (parser, target) = getparser()
442 parser.feed(data)
443 parser.close()
444 except IOError, msg:
445 print file, ":", msg
Daniel Veillard9589d452002-02-02 10:28:17 +0000446
447
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000448 print "Found %d functions in libxml2-python-api.xml" % (
449 len(functions.keys()) - n)
450 nb_wrap = 0
451 failed = 0
452 skipped = 0
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000453
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000454 include = open("libxml2-py.h", "w")
455 include.write("/* Generated */\n\n")
456 export = open("libxml2-export.c", "w")
457 export.write("/* Generated */\n\n")
458 wrapper = open("libxml2-py.c", "w")
459 wrapper.write("/* Generated */\n\n")
460 wrapper.write("#include <Python.h>\n")
461 wrapper.write("#include <libxml/tree.h>\n")
462 wrapper.write("#include \"libxml_wrap.h\"\n")
463 wrapper.write("#include \"libxml2-py.h\"\n\n")
464 for function in functions.keys():
465 ret = print_function_wrapper(function, wrapper, export, include)
466 if ret < 0:
467 failed = failed + 1
468 del functions[function]
469 if ret == 0:
470 skipped = skipped + 1
471 del functions[function]
472 if ret == 1:
473 nb_wrap = nb_wrap + 1
474 include.close()
475 export.close()
476 wrapper.close()
Daniel Veillardd2897fd2002-01-30 16:37:32 +0000477
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000478 print "Generated %d wrapper functions, %d failed, %d skipped\n" % (nb_wrap,
479 failed, skipped);
480 print "Missing type converters: "
481 for type in unknown_types.keys():
482 print "%s:%d " % (type, len(unknown_types[type])),
483 print
Daniel Veillard36ed5292002-01-30 23:49:06 +0000484
Daniel Veillard1971ee22002-01-31 20:29:19 +0000485#######################################################################
486#
487# This part writes part of the Python front-end classes based on
488# mapping rules between types and classes and also based on function
489# renaming to get consistent function names at the Python level
490#
491#######################################################################
492
493#
494# The type automatically remapped to generated classes
495#
496classes_type = {
497 "xmlNodePtr": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
498 "xmlNode *": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
499 "xmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
500 "xmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
501 "htmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
502 "htmlxmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
503 "xmlAttrPtr": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
504 "xmlAttr *": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
505 "xmlNsPtr": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
506 "xmlNs *": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
507 "xmlDtdPtr": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
508 "xmlDtd *": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
509 "xmlEntityPtr": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
510 "xmlEntity *": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
511 "xmlElementPtr": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
512 "xmlElement *": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
513 "xmlAttributePtr": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
514 "xmlAttribute *": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
515 "xmlXPathContextPtr": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
Daniel Veillard7db38712002-02-07 16:39:11 +0000516 "xmlXPathContext *": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
517 "xmlXPathParserContext *": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
518 "xmlXPathParserContextPtr": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
Daniel Veillard3ce52572002-02-03 15:08:05 +0000519 "xmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
520 "xmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
Daniel Veillard7db38712002-02-07 16:39:11 +0000521 "xmlCatalogPtr": ("._o", "catalog(_obj=%s)", "catalog"),
Daniel Veillard1971ee22002-01-31 20:29:19 +0000522}
523
524converter_type = {
525 "xmlXPathObjectPtr": "xpathObjectRet(%s)",
526}
527
528primary_classes = ["xmlNode", "xmlDoc"]
529
530classes_ancestor = {
531 "xmlNode" : "xmlCore",
Daniel Veillard253aa2c2002-02-02 09:17:16 +0000532 "xmlDtd" : "xmlNode",
533 "xmlDoc" : "xmlNode",
534 "xmlAttr" : "xmlNode",
535 "xmlNs" : "xmlNode",
536 "xmlEntity" : "xmlNode",
537 "xmlElement" : "xmlNode",
538 "xmlAttribute" : "xmlNode",
Daniel Veillard1971ee22002-01-31 20:29:19 +0000539}
540classes_destructors = {
Daniel Veillard3ce52572002-02-03 15:08:05 +0000541 "parserCtxt": "xmlFreeParserCtxt",
Daniel Veillard7db38712002-02-07 16:39:11 +0000542 "catalog": "xmlFreeCatalog",
Daniel Veillard1971ee22002-01-31 20:29:19 +0000543}
544
Daniel Veillard36ed5292002-01-30 23:49:06 +0000545function_classes = {}
Daniel Veillard1971ee22002-01-31 20:29:19 +0000546
547function_classes["None"] = []
Daniel Veillard1971ee22002-01-31 20:29:19 +0000548
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000549def nameFixup(name, classe, type, file):
Daniel Veillard1971ee22002-01-31 20:29:19 +0000550 listname = classe + "List"
551 ll = len(listname)
552 l = len(classe)
553 if name[0:l] == listname:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000554 func = name[l:]
555 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard3ce52572002-02-03 15:08:05 +0000556 elif name[0:12] == "xmlParserGet" and file == "python_accessor":
557 func = name[12:]
558 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard26f1dcc2002-02-03 16:53:19 +0000559 elif name[0:12] == "xmlParserSet" and file == "python_accessor":
560 func = name[12:]
561 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard36eea2d2002-02-04 00:17:01 +0000562 elif name[0:10] == "xmlNodeGet" and file == "python_accessor":
563 func = name[10:]
564 func = string.lower(func[0:1]) + func[1:]
Daniel Veillardc575b992002-02-08 13:28:40 +0000565 elif name[0:17] == "xmlXPathParserGet" and file == "python_accessor":
566 func = name[17:]
567 func = string.lower(func[0:1]) + func[1:]
568 elif name[0:11] == "xmlXPathGet" and file == "python_accessor":
569 func = name[11:]
570 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard7db38712002-02-07 16:39:11 +0000571 elif name[0:11] == "xmlACatalog":
572 func = name[11:]
573 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard1971ee22002-01-31 20:29:19 +0000574 elif name[0:l] == classe:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000575 func = name[l:]
576 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard9589d452002-02-02 10:28:17 +0000577 elif name[0:7] == "libxml_":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000578 func = name[7:]
579 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard1971ee22002-01-31 20:29:19 +0000580 elif name[0:6] == "xmlGet":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000581 func = name[6:]
582 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard1971ee22002-01-31 20:29:19 +0000583 elif name[0:3] == "xml":
Daniel Veillard01a6d412002-02-11 18:42:20 +0000584 func = name[3:]
585 func = string.lower(func[0:1]) + func[1:]
Daniel Veillard36ed5292002-01-30 23:49:06 +0000586 else:
Daniel Veillard1971ee22002-01-31 20:29:19 +0000587 func = name
588 if func[0:5] == "xPath":
589 func = "xpath" + func[5:]
590 elif func[0:4] == "xPtr":
591 func = "xpointer" + func[4:]
592 elif func[0:8] == "xInclude":
593 func = "xinclude" + func[8:]
594 elif func[0:2] == "iD":
595 func = "ID" + func[2:]
596 elif func[0:3] == "uRI":
597 func = "URI" + func[3:]
598 elif func[0:4] == "uTF8":
599 func = "UTF8" + func[4:]
600 return func
Daniel Veillard36ed5292002-01-30 23:49:06 +0000601
Daniel Veillard36ed5292002-01-30 23:49:06 +0000602
Daniel Veillard1971ee22002-01-31 20:29:19 +0000603def functionCompare(info1, info2):
604 (index1, func1, name1, ret1, args1, file1) = info1
605 (index2, func2, name2, ret2, args2, file2) = info2
Daniel Veillard26f1dcc2002-02-03 16:53:19 +0000606 if file1 == file2:
Daniel Veillard01a6d412002-02-11 18:42:20 +0000607 if func1 < func2:
608 return -1
609 if func1 > func2:
610 return 1
Daniel Veillard3ce52572002-02-03 15:08:05 +0000611 if file1 == "python_accessor":
612 return -1
613 if file2 == "python_accessor":
614 return 1
Daniel Veillard1971ee22002-01-31 20:29:19 +0000615 if file1 < file2:
616 return -1
617 if file1 > file2:
618 return 1
Daniel Veillard1971ee22002-01-31 20:29:19 +0000619 return 0
620
621def writeDoc(name, args, indent, output):
622 if functions[name][0] == None or functions[name][0] == "":
623 return
624 val = functions[name][0]
625 val = string.replace(val, "NULL", "None");
626 output.write(indent)
627 output.write('"""')
628 while len(val) > 60:
629 str = val[0:60]
Daniel Veillard01a6d412002-02-11 18:42:20 +0000630 i = string.rfind(str, " ");
631 if i < 0:
632 i = 60
Daniel Veillard1971ee22002-01-31 20:29:19 +0000633 str = val[0:i]
Daniel Veillard01a6d412002-02-11 18:42:20 +0000634 val = val[i:]
635 output.write(str)
636 output.write('\n ');
637 output.write(indent)
Daniel Veillard1971ee22002-01-31 20:29:19 +0000638 output.write(val);
639 output.write('"""\n')
640
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000641def buildWrappers():
642 global ctypes
643 global py_types
644 global py_return_types
645 global unknown_types
646 global functions
647 global function_classes
648 global classes_type
649 global classes_list
650 global converter_type
651 global primary_classes
652 global converter_type
653 global classes_ancestor
654 global converter_type
655 global primary_classes
656 global classes_ancestor
657 global classes_destructors
Daniel Veillard36eea2d2002-02-04 00:17:01 +0000658
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000659 for type in classes_type.keys():
660 function_classes[classes_type[type][2]] = []
Daniel Veillard36ed5292002-01-30 23:49:06 +0000661
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000662 #
663 # Build the list of C types to look for ordered to start
664 # with primary classes
665 #
666 ctypes = []
667 classes_list = []
668 ctypes_processed = {}
669 classes_processed = {}
670 for classe in primary_classes:
671 classes_list.append(classe)
672 classes_processed[classe] = ()
673 for type in classes_type.keys():
674 tinfo = classes_type[type]
675 if tinfo[2] == classe:
676 ctypes.append(type)
677 ctypes_processed[type] = ()
678 for type in classes_type.keys():
679 if ctypes_processed.has_key(type):
680 continue
681 tinfo = classes_type[type]
682 if not classes_processed.has_key(tinfo[2]):
683 classes_list.append(tinfo[2])
684 classes_processed[tinfo[2]] = ()
685
686 ctypes.append(type)
687 ctypes_processed[type] = ()
Daniel Veillard36ed5292002-01-30 23:49:06 +0000688
Daniel Veillard0fea6f42002-02-22 22:51:13 +0000689 for name in functions.keys():
690 found = 0;
691 (desc, ret, args, file) = functions[name]
692 for type in ctypes:
693 classe = classes_type[type][2]
694
695 if name[0:3] == "xml" and len(args) >= 1 and args[0][1] == type:
696 found = 1
697 func = nameFixup(name, classe, type, file)
698 info = (0, func, name, ret, args, file)
699 function_classes[classe].append(info)
700 elif name[0:3] == "xml" and len(args) >= 2 and args[1][1] == type:
701 found = 1
702 func = nameFixup(name, classe, type, file)
703 info = (1, func, name, ret, args, file)
704 function_classes[classe].append(info)
705 elif name[0:4] == "html" and len(args) >= 1 and args[0][1] == type:
706 found = 1
707 func = nameFixup(name, classe, type, file)
708 info = (0, func, name, ret, args, file)
709 function_classes[classe].append(info)
710 elif name[0:4] == "html" and len(args) >= 2 and args[1][1] == type:
711 found = 1
712 func = nameFixup(name, classe, type, file)
713 info = (1, func, name, ret, args, file)
714 function_classes[classe].append(info)
715 if found == 1:
716 break
717 if found == 1:
718 continue
719 if name[0:8] == "xmlXPath":
720 continue
721 if name[0:6] == "xmlStr":
722 continue
723 if name[0:10] == "xmlCharStr":
724 continue
725 func = nameFixup(name, "None", file, file)
726 info = (0, func, name, ret, args, file)
727 function_classes['None'].append(info)
728
729 classes = open("libxml2class.py", "w")
730 txt = open("libxml2class.txt", "w")
731 txt.write(" Generated Classes for libxml2-python\n\n")
732
733 txt.write("#\n# Global functions of the module\n#\n\n")
734 if function_classes.has_key("None"):
735 flist = function_classes["None"]
736 flist.sort(functionCompare)
737 oldfile = ""
738 for info in flist:
739 (index, func, name, ret, args, file) = info
740 if file != oldfile:
741 classes.write("#\n# Functions from module %s\n#\n\n" % file)
742 txt.write("\n# functions from module %s\n" % file)
743 oldfile = file
744 classes.write("def %s(" % func)
745 txt.write("%s()\n" % func);
746 n = 0
747 for arg in args:
748 if n != 0:
749 classes.write(", ")
750 classes.write("%s" % arg[0])
751 n = n + 1
752 classes.write("):\n")
753 writeDoc(name, args, ' ', classes);
754
755 for arg in args:
756 if classes_type.has_key(arg[1]):
757 classes.write(" if %s == None: %s__o = None\n" %
758 (arg[0], arg[0]))
759 classes.write(" else: %s__o = %s%s\n" %
760 (arg[0], arg[0], classes_type[arg[1]][0]))
761 if ret[0] != "void":
762 classes.write(" ret = ");
763 else:
764 classes.write(" ");
765 classes.write("libxml2mod.%s(" % name)
766 n = 0
767 for arg in args:
768 if n != 0:
769 classes.write(", ");
770 classes.write("%s" % arg[0])
771 if classes_type.has_key(arg[1]):
772 classes.write("__o");
773 n = n + 1
774 classes.write(")\n");
775 if ret[0] != "void":
776 if classes_type.has_key(ret[0]):
777 classes.write(" if ret == None: return None\n");
778 classes.write(" return ");
779 classes.write(classes_type[ret[0]][1] % ("ret"));
780 classes.write("\n");
781 else:
782 classes.write(" return ret\n");
783 classes.write("\n");
784
785 txt.write("\n\n#\n# Set of classes of the module\n#\n\n")
786 for classname in classes_list:
787 if classname == "None":
788 pass
789 else:
790 if classes_ancestor.has_key(classname):
791 txt.write("\n\nClass %s(%s)\n" % (classname,
792 classes_ancestor[classname]))
793 classes.write("class %s(%s):\n" % (classname,
794 classes_ancestor[classname]))
795 classes.write(" def __init__(self, _obj=None):\n")
796 classes.write(" self._o = None\n")
797 classes.write(" %s.__init__(self, _obj=_obj)\n\n" % (
798 classes_ancestor[classname]))
799 if classes_ancestor[classname] == "xmlCore" or \
800 classes_ancestor[classname] == "xmlNode":
801 classes.write(" def __repr__(self):\n")
802 format = "%s:%%s" % (classname)
803 classes.write(" return \"%s\" %% (self.name)\n\n" % (
804 format))
805 else:
806 txt.write("Class %s()\n" % (classname))
807 classes.write("class %s:\n" % (classname))
808 classes.write(" def __init__(self, _obj=None):\n")
809 classes.write(" if _obj != None:self._o = _obj;return\n")
810 classes.write(" self._o = None\n\n");
811 if classes_destructors.has_key(classname):
812 classes.write(" def __del__(self):\n")
813 classes.write(" if self._o != None:\n")
814 classes.write(" libxml2mod.%s(self._o)\n" %
815 classes_destructors[classname]);
816 classes.write(" self._o = None\n\n");
817 flist = function_classes[classname]
818 flist.sort(functionCompare)
819 oldfile = ""
820 for info in flist:
821 (index, func, name, ret, args, file) = info
822 if file != oldfile:
823 if file == "python_accessor":
824 classes.write(" # accessors for %s\n" % (classname))
825 txt.write(" # accessors\n")
826 else:
827 classes.write(" #\n")
828 classes.write(" # %s functions from module %s\n" % (
829 classname, file))
830 txt.write("\n # functions from module %s\n" % file)
831 classes.write(" #\n\n")
832 oldfile = file
833 classes.write(" def %s(self" % func)
834 txt.write(" %s()\n" % func);
835 n = 0
836 for arg in args:
837 if n != index:
838 classes.write(", %s" % arg[0])
839 n = n + 1
840 classes.write("):\n")
841 writeDoc(name, args, ' ', classes);
842 n = 0
843 for arg in args:
844 if classes_type.has_key(arg[1]):
845 if n != index:
846 classes.write(" if %s == None: %s__o = None\n" %
847 (arg[0], arg[0]))
848 classes.write(" else: %s__o = %s%s\n" %
849 (arg[0], arg[0], classes_type[arg[1]][0]))
850 n = n + 1
851 if ret[0] != "void":
852 classes.write(" ret = ");
853 else:
854 classes.write(" ");
855 classes.write("libxml2mod.%s(" % name)
856 n = 0
857 for arg in args:
858 if n != 0:
859 classes.write(", ");
860 if n != index:
861 classes.write("%s" % arg[0])
862 if classes_type.has_key(arg[1]):
863 classes.write("__o");
864 else:
865 classes.write("self");
866 if classes_type.has_key(arg[1]):
867 classes.write(classes_type[arg[1]][0])
868 n = n + 1
869 classes.write(")\n");
870 if ret[0] != "void":
871 if classes_type.has_key(ret[0]):
872 classes.write(" if ret == None: return None\n");
873 classes.write(" return ");
874 classes.write(classes_type[ret[0]][1] % ("ret"));
875 classes.write("\n");
876 elif converter_type.has_key(ret[0]):
877 classes.write(" if ret == None: return None\n");
878 classes.write(" return ");
879 classes.write(converter_type[ret[0]] % ("ret"));
880 classes.write("\n");
881 else:
882 classes.write(" return ret\n");
883 classes.write("\n");
884
885 txt.close()
886 classes.close()
887
888
889buildStubs()
890buildWrappers()