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