VirtualBox

source: vbox/trunk/src/libs/libxslt-1.1.22/python/generator.py@ 15017

最後變更 在這個檔案從15017是 7296,由 vboxsync 提交於 17 年 前

Added libxslt-1.1.22 sources.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Date Revision Author Id
檔案大小: 34.7 KB
 
1#!/usr/bin/python -u
2#
3# generate python wrappers from the XML API description
4#
5
6functions = {}
7enums = {} # { enumType: { enumConstant: enumValue } }
8
9import string
10
11#######################################################################
12#
13# That part if purely the API acquisition phase from the
14# XML API description
15#
16#######################################################################
17import os
18import xmllib
19try:
20 import sgmlop
21except ImportError:
22 sgmlop = None # accelerator not available
23
24debug = 0
25
26if 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
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):
69 self.unknown_starttag = target.start
70 self.handle_data = target.data
71 self.unknown_endtag = target.end
72 xmllib.XMLParser.__init__(self)
73
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:
78 target = docParser()
79 if FastParser:
80 return FastParser(target), target
81 return SlowParser(target), target
82
83class 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 elif tag == 'enum':
141 enum(attrs['type'],attrs['name'],attrs['value'])
142
143
144
145 def end(self, tag):
146 if debug:
147 print "end %s" % tag
148 if tag == 'function':
149 if self.function != None:
150 function(self.function, self.function_descr,
151 self.function_return, self.function_args,
152 self.function_file)
153 self.in_function = 0
154 elif tag == 'arg':
155 if self.in_function == 1:
156 self.function_args.append([self.function_arg_name,
157 self.function_arg_type,
158 self.function_arg_info])
159 elif tag == 'return':
160 if self.in_function == 1:
161 self.function_return = [self.function_return_type,
162 self.function_return_info,
163 self.function_return_field]
164 elif tag == 'info':
165 str = ''
166 for c in self._data:
167 str = str + c
168 if self.in_function == 1:
169 self.function_descr = str
170
171
172def function(name, desc, ret, args, file):
173 functions[name] = (desc, ret, args, file)
174
175def enum(type, name, value):
176 if not enums.has_key(type):
177 enums[type] = {}
178 enums[type][name] = value
179
180#######################################################################
181#
182# Some filtering rukes to drop functions/types which should not
183# be exposed as-is on the Python interface
184#
185#######################################################################
186
187skipped_modules = {
188 'xmlmemory': None,
189 'DOCBparser': None,
190 'SAX': None,
191 'hash': None,
192 'list': None,
193 'threads': None,
194 'xpointer': None,
195 'transform': None,
196}
197skipped_types = {
198 'int *': "usually a return type",
199 'xmlSAXHandlerPtr': "not the proper interface for SAX",
200 'htmlSAXHandlerPtr': "not the proper interface for SAX",
201 'xmlRMutexPtr': "thread specific, skipped",
202 'xmlMutexPtr': "thread specific, skipped",
203 'xmlGlobalStatePtr': "thread specific, skipped",
204 'xmlListPtr': "internal representation not suitable for python",
205 'xmlBufferPtr': "internal representation not suitable for python",
206 'FILE *': None,
207}
208
209#######################################################################
210#
211# Table of remapping to/from the python type or class to the C
212# counterpart.
213#
214#######################################################################
215
216py_types = {
217 'void': (None, None, None, None, None),
218 'int': ('i', None, "int", "int", "libxml_"),
219 'long': ('l', None, "long", "long", "libxml_"),
220 'double': ('d', None, "double", "double", "libxml_"),
221 'unsigned int': ('i', None, "int", "int", "libxml_"),
222 'xmlChar': ('c', None, "int", "int", "libxml_"),
223 'unsigned char *': ('z', None, "charPtr", "char *", "libxml_"),
224 'char *': ('z', None, "charPtr", "char *", "libxml_"),
225 'const char *': ('z', None, "charPtrConst", "const char *", "libxml_"),
226 'xmlChar *': ('z', None, "xmlCharPtr", "xmlChar *", "libxml_"),
227 'const xmlChar *': ('z', None, "xmlCharPtrConst", "const xmlChar *", "libxml_"),
228 'xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
229 'const xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
230 'xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
231 'const xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
232 'xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
233 'const xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
234 'xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
235 'const xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
236 'xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
237 'const xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
238 'xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
239 'const xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
240 'xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
241 'const xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
242 'xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
243 'const xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
244 'xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr", "libxml_"),
245 'const xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr", "libxml_"),
246 'xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr", "libxml_"),
247 'const xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr", "libxml_"),
248 'xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr", "libxml_"),
249 'const xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr", "libxml_"),
250 'xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr", "libxml_"),
251 'const xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr", "libxml_"),
252 'xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr", "libxml_"),
253 'const xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr", "libxml_"),
254 'xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr", "libxml_"),
255 'const xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr", "libxml_"),
256 'xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
257 'const xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
258 'xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
259 'const xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
260 'htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
261 'const htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
262 'htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
263 'const htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr", "libxml_"),
264 'htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
265 'const htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
266 'htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
267 'const htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr", "libxml_"),
268 'xmlXPathContextPtr': ('O', "xmlXPathContext", "xmlXPathContextPtr", "xmlXPathContextPtr", "libxml_"),
269 'xmlXPathParserContextPtr': ('O', "xmlXPathParserContext", "xmlXPathParserContextPtr", "xmlXPathParserContextPtr", "libxml_"),
270 'xmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr", "libxml_"),
271 'xmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr", "libxml_"),
272 'htmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr", "libxml_"),
273 'htmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr", "libxml_"),
274 'xmlCatalogPtr': ('O', "catalog", "xmlCatalogPtr", "xmlCatalogPtr"),
275 'FILE *': ('O', "File", "FILEPtr", "FILE *", "libxml_"),
276 'xsltTransformContextPtr': ('O', "transformCtxt", "xsltTransformContextPtr", "xsltTransformContextPtr", "libxslt_"),
277 'xsltTransformContext *': ('O', "transformCtxt", "xsltTransformContextPtr", "xsltTransformContextPtr", "libxslt_"),
278 'xsltStylePreCompPtr': ('O', "compiledStyle", "xsltStylePreCompPtr", "xsltStylePreCompPtr", "libxslt_"),
279 'xsltStylePreComp *': ('O', "compiledStyle", "xsltStylePreCompPtr", "xsltStylePreCompPtr", "libxslt_"),
280 'xsltStylesheetPtr': ('O', "stylesheet", "xsltStylesheetPtr", "xsltStylesheetPtr", "libxslt_"),
281 'xsltStylesheet *': ('O', "stylesheet", "xsltStylesheetPtr", "xsltStylesheetPtr", "libxslt_"),
282 'xmlXPathContext *': ('O', "xpathContext", "xmlXPathContextPtr", "xmlXPathContextPtr", "libxslt_"),
283}
284
285py_return_types = {
286 'xmlXPathObjectPtr': ('O', "foo", "xmlXPathObjectPtr", "xmlXPathObjectPtr", "libxml_"),
287}
288
289unknown_types = {}
290
291#######################################################################
292#
293# This part writes the C <-> Python stubs libxslt-py.[ch] and
294# the table libxslt-export.c to add when registrering the Python module
295#
296#######################################################################
297
298def skip_function(name):
299 if name[0:12] == "xmlXPathWrap":
300 return 1
301 if name == "xsltMatchPattern":
302 return 1
303# if name[0:11] == "xmlXPathNew":
304# return 1
305 return 0
306
307def print_function_wrapper(name, output, export, include):
308 global py_types
309 global unknown_types
310 global functions
311 global skipped_modules
312
313 try:
314 (desc, ret, args, file) = functions[name]
315 except:
316 print "failed to get function %s infos"
317 return
318
319 if skipped_modules.has_key(file):
320 return 0
321 if skip_function(name) == 1:
322 return 0
323
324 c_call = "";
325 format=""
326 format_args=""
327 c_args=""
328 c_return=""
329 c_convert=""
330 for arg in args:
331 # This should be correct
332 if arg[1][0:6] == "const ":
333 arg[1] = arg[1][6:]
334 c_args = c_args + " %s %s;\n" % (arg[1], arg[0])
335 if py_types.has_key(arg[1]):
336 (f, t, n, c, p) = py_types[arg[1]]
337 if f != None:
338 format = format + f
339 if t != None:
340 format_args = format_args + ", &pyobj_%s" % (arg[0])
341 c_args = c_args + " PyObject *pyobj_%s;\n" % (arg[0])
342 c_convert = c_convert + \
343 " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0],
344 arg[1], t, arg[0]);
345 else:
346 format_args = format_args + ", &%s" % (arg[0])
347 if c_call != "":
348 c_call = c_call + ", ";
349 c_call = c_call + "%s" % (arg[0])
350 else:
351 if skipped_types.has_key(arg[1]):
352 return 0
353 if unknown_types.has_key(arg[1]):
354 lst = unknown_types[arg[1]]
355 lst.append(name)
356 else:
357 unknown_types[arg[1]] = [name]
358 return -1
359 if format != "":
360 format = format + ":%s" % (name)
361
362 if ret[0] == 'void':
363 if file == "python_accessor":
364 if args[1][1] == "char *" or args[1][1] == "xmlChar *":
365 c_call = "\n if (%s->%s != NULL) xmlFree(%s->%s);\n" % (
366 args[0][0], args[1][0], args[0][0], args[1][0])
367 c_call = c_call + " %s->%s = xmlStrdup((const xmlChar *)%s);\n" % (args[0][0],
368 args[1][0], args[1][0])
369 else:
370 c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0],
371 args[1][0])
372 else:
373 c_call = "\n %s(%s);\n" % (name, c_call);
374 ret_convert = " Py_INCREF(Py_None);\n return(Py_None);\n"
375 elif py_types.has_key(ret[0]):
376 (f, t, n, c, p) = py_types[ret[0]]
377 c_return = " %s c_retval;\n" % (ret[0])
378 if file == "python_accessor" and ret[2] != None:
379 c_call = "\n c_retval = %s->%s;\n" % (args[0][0], ret[2])
380 else:
381 c_call = "\n c_retval = %s(%s);\n" % (name, c_call);
382 ret_convert = " py_retval = %s%sWrap((%s) c_retval);\n" % (p,n,c)
383 ret_convert = ret_convert + " return(py_retval);\n"
384 elif py_return_types.has_key(ret[0]):
385 (f, t, n, c, p) = py_return_types[ret[0]]
386 c_return = " %s c_retval;\n" % (ret[0])
387 if file == "python_accessor" and ret[2] != None:
388 c_call = "\n c_retval = %s->%s;\n" % (args[0][0], ret[2])
389 else:
390 c_call = "\n c_retval = %s(%s);\n" % (name, c_call);
391 ret_convert = " py_retval = %s%sWrap((%s) c_retval);\n" % (p,n,c)
392 ret_convert = ret_convert + " return(py_retval);\n"
393 else:
394 if skipped_types.has_key(ret[0]):
395 return 0
396 if unknown_types.has_key(ret[0]):
397 lst = unknown_types[ret[0]]
398 lst.append(name)
399 else:
400 unknown_types[ret[0]] = [name]
401 return -1
402
403 include.write("PyObject * ")
404 include.write("libxslt_%s(PyObject *self, PyObject *args);\n" % (name))
405
406 export.write(" { (char *)\"%s\", libxslt_%s, METH_VARARGS, NULL },\n" % (name, name))
407
408 if file == "python":
409 # Those have been manually generated
410 return 1
411 if file == "python_accessor" and ret[0] != "void" and ret[2] == None:
412 # Those have been manually generated
413 return 1
414
415 output.write("PyObject *\n")
416 output.write("libxslt_%s(PyObject *self ATTRIBUTE_UNUSED," % (name))
417 output.write(" PyObject *args")
418 if format == "":
419 output.write(" ATTRIBUTE_UNUSED")
420 output.write(") {\n")
421 if ret[0] != 'void':
422 output.write(" PyObject *py_retval;\n")
423 if c_return != "":
424 output.write(c_return)
425 if c_args != "":
426 output.write(c_args)
427 if format != "":
428 output.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
429 (format, format_args))
430 output.write(" return(NULL);\n")
431 if c_convert != "":
432 output.write(c_convert)
433
434 output.write(c_call)
435 output.write(ret_convert)
436 output.write("}\n\n")
437 return 1
438
439def buildStubs():
440 global py_types
441 global py_return_types
442 global unknown_types
443
444 try:
445 f = open("libxslt-api.xml")
446 data = f.read()
447 (parser, target) = getparser()
448 parser.feed(data)
449 parser.close()
450 except IOError, msg:
451 try:
452 f = open("../doc/libxslt-api.xml")
453 data = f.read()
454 (parser, target) = getparser()
455 parser.feed(data)
456 parser.close()
457 except IOError, msg:
458 print "../doc/libxslt-api.xml", ":", msg
459
460 n = len(functions.keys())
461 print "Found %d functions in libxslt-api.xml" % (n)
462
463 py_types['pythonObject'] = ('O', "pythonObject", "pythonObject",
464 "pythonObject", "libxml_")
465 try:
466 f = open("libxslt-python-api.xml")
467 data = f.read()
468 (parser, target) = getparser()
469 parser.feed(data)
470 parser.close()
471 except IOError, msg:
472 print "libxslt-python-api.xml", ":", msg
473
474
475 print "Found %d functions in libxslt-python-api.xml" % (
476 len(functions.keys()) - n)
477 nb_wrap = 0
478 failed = 0
479 skipped = 0
480
481 include = open("libxslt-py.h", "w")
482 include.write("/* Generated */\n\n")
483 export = open("libxslt-export.c", "w")
484 export.write("/* Generated */\n\n")
485 wrapper = open("libxslt-py.c", "w")
486 wrapper.write("/* Generated */\n\n")
487# wrapper.write("#include \"config.h\"\n")
488 wrapper.write("#include <libxslt/xsltconfig.h>\n")
489 wrapper.write("#include \"libxslt_wrap.h\"\n")
490 wrapper.write("#include \"libxslt-py.h\"\n\n")
491 for function in functions.keys():
492 ret = print_function_wrapper(function, wrapper, export, include)
493 if ret < 0:
494 failed = failed + 1
495 del functions[function]
496 if ret == 0:
497 skipped = skipped + 1
498 del functions[function]
499 if ret == 1:
500 nb_wrap = nb_wrap + 1
501 include.close()
502 export.close()
503 wrapper.close()
504
505 print "Generated %d wrapper functions, %d failed, %d skipped\n" % (nb_wrap,
506 failed, skipped);
507 print "Missing type converters:"
508 for type in unknown_types.keys():
509 print "%s:%d " % (type, len(unknown_types[type])),
510 print
511
512#######################################################################
513#
514# This part writes part of the Python front-end classes based on
515# mapping rules between types and classes and also based on function
516# renaming to get consistent function names at the Python level
517#
518#######################################################################
519
520#
521# The type automatically remapped to generated classes
522#
523libxml2_classes_type = {
524 "xmlNodePtr": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
525 "xmlNode *": ("._o", "xmlNode(_obj=%s)", "xmlNode"),
526 "xmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
527 "xmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
528 "htmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
529 "htmlxmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"),
530 "xmlAttrPtr": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
531 "xmlAttr *": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"),
532 "xmlNsPtr": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
533 "xmlNs *": ("._o", "xmlNs(_obj=%s)", "xmlNs"),
534 "xmlDtdPtr": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
535 "xmlDtd *": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"),
536 "xmlEntityPtr": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
537 "xmlEntity *": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"),
538 "xmlElementPtr": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
539 "xmlElement *": ("._o", "xmlElement(_obj=%s)", "xmlElement"),
540 "xmlAttributePtr": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
541 "xmlAttribute *": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"),
542 "xmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
543 "xmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"),
544 "xmlCatalogPtr": ("._o", "catalog(_obj=%s)", "catalog"),
545}
546
547classes_type = {
548 "xsltTransformContextPtr": ("._o", "transformCtxt(_obj=%s)", "transformCtxt"),
549 "xsltTransformContext *": ("._o", "transformCtxt(_obj=%s)", "transformCtxt"),
550 "xsltStylesheetPtr": ("._o", "stylesheet(_obj=%s)", "stylesheet"),
551 "xsltStylesheet *": ("._o", "stylesheet(_obj=%s)", "stylesheet"),
552 "xmlXPathContextPtr": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
553 "xmlXPathContext *": ("._o", "xpathContext(_obj=%s)", "xpathContext"),
554 "xmlXPathParserContextPtr": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
555 "xmlXPathParserContext *": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"),
556}
557
558converter_type = {
559 "xmlXPathObjectPtr": "libxml2.xpathObjectRet(%s)",
560}
561
562primary_classes = ["xpathParserContext", "xpathContext", "transformCtxt", "stylesheet"]
563
564classes_ancestor = {
565 "xpathContext" : "libxml2.xpathContext",
566 "xpathParserContext" : "libxml2.xpathParserContext",
567 "transformCtxt": "transformCtxtBase",
568 "stylesheet": "stylesheetBase",
569}
570classes_destructors = {
571 "xpathContext" : "pass"
572}
573
574function_classes = {}
575ctypes = []
576classes_list = []
577
578
579def nameFixup(name, classe, type, file):
580 listname = classe + "List"
581 ll = len(listname)
582 l = len(classe)
583 if name[0:l] == listname:
584 func = name[l:]
585 func = string.lower(func[0:1]) + func[1:]
586 elif name[0:12] == "xmlParserGet" and file == "python_accessor":
587 func = name[12:]
588 func = string.lower(func[0:1]) + func[1:]
589 elif name[0:12] == "xmlParserSet" and file == "python_accessor":
590 func = name[12:]
591 func = string.lower(func[0:1]) + func[1:]
592 elif name[0:10] == "xmlNodeGet" and file == "python_accessor":
593 func = name[10:]
594 func = string.lower(func[0:1]) + func[1:]
595 elif name[0:18] == "xsltXPathParserGet" and file == "python_accessor":
596 func = name[18:]
597 func = string.lower(func[0:1]) + func[1:]
598 elif name[0:12] == "xsltXPathGet" and file == "python_accessor":
599 func = name[12:]
600 func = string.lower(func[0:1]) + func[1:]
601 elif name[0:16] == "xsltTransformGet" and file == "python_accessor":
602 func = name[16:]
603 func = string.lower(func[0:1]) + func[1:]
604 elif name[0:16] == "xsltTransformSet" and file == "python_accessor":
605 func = name[13:]
606 func = string.lower(func[0:1]) + func[1:]
607 elif name[0:17] == "xsltStylesheetGet" and file == "python_accessor":
608 func = name[17:]
609 func = string.lower(func[0:1]) + func[1:]
610 elif name[0:17] == "xsltStylesheetSet" and file == "python_accessor":
611 func = name[14:]
612 func = string.lower(func[0:1]) + func[1:]
613 elif name[0:l] == classe:
614 func = name[l:]
615 func = string.lower(func[0:1]) + func[1:]
616 elif name[0:7] == "libxml_":
617 func = name[7:]
618 func = string.lower(func[0:1]) + func[1:]
619 elif name[0:8] == "libxslt_":
620 func = name[8:]
621 func = string.lower(func[0:1]) + func[1:]
622 elif name[0:6] == "xmlGet":
623 func = name[6:]
624 func = string.lower(func[0:1]) + func[1:]
625 elif name[0:3] == "xml":
626 func = name[3:]
627 func = string.lower(func[0:1]) + func[1:]
628 elif name[0:7] == "xsltGet":
629 func = name[7:]
630 func = string.lower(func[0:1]) + func[1:]
631 elif name[0:4] == "xslt":
632 func = name[4:]
633 func = string.lower(func[0:1]) + func[1:]
634 else:
635 func = name
636 if func[0:5] == "xPath":
637 func = "xpath" + func[5:]
638 elif func[0:4] == "xPtr":
639 func = "xpointer" + func[4:]
640 elif func[0:8] == "xInclude":
641 func = "xinclude" + func[8:]
642 elif func[0:2] == "iD":
643 func = "ID" + func[2:]
644 elif func[0:3] == "uRI":
645 func = "URI" + func[3:]
646 elif func[0:4] == "uTF8":
647 func = "UTF8" + func[4:]
648 return func
649
650def functionCompare(info1, info2):
651 (index1, func1, name1, ret1, args1, file1) = info1
652 (index2, func2, name2, ret2, args2, file2) = info2
653 if file1 == file2:
654 if func1 < func2:
655 return -1
656 if func1 > func2:
657 return 1
658 if file1 == "python_accessor":
659 return -1
660 if file2 == "python_accessor":
661 return 1
662 if file1 < file2:
663 return -1
664 if file1 > file2:
665 return 1
666 return 0
667
668def writeDoc(name, args, indent, output):
669 if functions[name][0] == None or functions[name][0] == "":
670 return
671 val = functions[name][0]
672 val = string.replace(val, "NULL", "None");
673 output.write(indent)
674 output.write('"""')
675 while len(val) > 60:
676 str = val[0:60]
677 i = string.rfind(str, " ");
678 if i < 0:
679 i = 60
680 str = val[0:i]
681 val = val[i:]
682 output.write(str)
683 output.write('\n ');
684 output.write(indent)
685 output.write(val);
686 output.write('"""\n')
687
688def buildWrappers():
689 global ctypes
690 global py_types
691 global py_return_types
692 global unknown_types
693 global functions
694 global function_classes
695 global libxml2_classes_type
696 global classes_type
697 global classes_list
698 global converter_type
699 global primary_classes
700 global converter_type
701 global classes_ancestor
702 global converter_type
703 global primary_classes
704 global classes_ancestor
705 global classes_destructors
706
707 function_classes["None"] = []
708 for type in classes_type.keys():
709 function_classes[classes_type[type][2]] = []
710
711 #
712 # Build the list of C types to look for ordered to start with
713 # primary classes
714 #
715 ctypes_processed = {}
716 classes_processed = {}
717 for classe in primary_classes:
718 classes_list.append(classe)
719 classes_processed[classe] = ()
720 for type in classes_type.keys():
721 tinfo = classes_type[type]
722 if tinfo[2] == classe:
723 ctypes.append(type)
724 ctypes_processed[type] = ()
725 for type in classes_type.keys():
726 if ctypes_processed.has_key(type):
727 continue
728 tinfo = classes_type[type]
729 if not classes_processed.has_key(tinfo[2]):
730 classes_list.append(tinfo[2])
731 classes_processed[tinfo[2]] = ()
732
733 ctypes.append(type)
734 ctypes_processed[type] = ()
735
736 for name in functions.keys():
737 found = 0;
738 (desc, ret, args, file) = functions[name]
739 for type in ctypes:
740 classe = classes_type[type][2]
741
742 if name[0:4] == "xslt" and len(args) >= 1 and args[0][1] == type:
743 found = 1
744 func = nameFixup(name, classe, type, file)
745 info = (0, func, name, ret, args, file)
746 function_classes[classe].append(info)
747 elif name[0:4] == "xslt" and len(args) >= 2 and args[1][1] == type:
748 found = 1
749 func = nameFixup(name, classe, type, file)
750 info = (1, func, name, ret, args, file)
751 function_classes[classe].append(info)
752 elif name[0:4] == "xslt" and len(args) >= 3 and args[2][1] == type:
753 found = 1
754 func = nameFixup(name, classe, type, file)
755 info = (2, func, name, ret, args, file)
756 function_classes[classe].append(info)
757 if found == 1:
758 continue
759 if name[0:8] == "xmlXPath":
760 continue
761 if name[0:6] == "xmlStr":
762 continue
763 if name[0:10] == "xmlCharStr":
764 continue
765 func = nameFixup(name, "None", file, file)
766 info = (0, func, name, ret, args, file)
767 function_classes['None'].append(info)
768
769 classes = open("libxsltclass.py", "w")
770 txt = open("libxsltclass.txt", "w")
771 txt.write(" Generated Classes for libxslt-python\n\n")
772
773 txt.write("#\n# Global functions of the module\n#\n\n")
774 if function_classes.has_key("None"):
775 flist = function_classes["None"]
776 flist.sort(functionCompare)
777 oldfile = ""
778 for info in flist:
779 (index, func, name, ret, args, file) = info
780 if file != oldfile:
781 classes.write("#\n# Functions from module %s\n#\n\n" % file)
782 txt.write("\n# functions from module %s\n" % file)
783 oldfile = file
784 classes.write("def %s(" % func)
785 txt.write("%s()\n" % func);
786 n = 0
787 for arg in args:
788 if n != 0:
789 classes.write(", ")
790 classes.write("%s" % arg[0])
791 n = n + 1
792 classes.write("):\n")
793 writeDoc(name, args, ' ', classes);
794
795 for arg in args:
796 if classes_type.has_key(arg[1]):
797 classes.write(" if %s == None: %s__o = None\n" %
798 (arg[0], arg[0]))
799 classes.write(" else: %s__o = %s%s\n" %
800 (arg[0], arg[0], classes_type[arg[1]][0]))
801 elif libxml2_classes_type.has_key(arg[1]):
802 classes.write(" if %s == None: %s__o = None\n" %
803 (arg[0], arg[0]))
804 classes.write(" else: %s__o = %s%s\n" %
805 (arg[0], arg[0], libxml2_classes_type[arg[1]][0]))
806 if ret[0] != "void":
807 classes.write(" ret = ");
808 else:
809 classes.write(" ");
810 classes.write("libxsltmod.%s(" % name)
811 n = 0
812 for arg in args:
813 if n != 0:
814 classes.write(", ");
815 classes.write("%s" % arg[0])
816 if classes_type.has_key(arg[1]):
817 classes.write("__o");
818 if libxml2_classes_type.has_key(arg[1]):
819 classes.write("__o");
820 n = n + 1
821 classes.write(")\n");
822 if ret[0] != "void":
823 if classes_type.has_key(ret[0]):
824 classes.write(" if ret == None: return None\n");
825 classes.write(" return ");
826 classes.write(classes_type[ret[0]][1] % ("ret"));
827 classes.write("\n");
828 elif libxml2_classes_type.has_key(ret[0]):
829 classes.write(" if ret == None: return None\n");
830 classes.write(" return libxml2.");
831 classes.write(libxml2_classes_type[ret[0]][1] % ("ret"));
832 classes.write("\n");
833 else:
834 classes.write(" return ret\n");
835 classes.write("\n");
836
837 txt.write("\n\n#\n# Set of classes of the module\n#\n\n")
838 for classname in classes_list:
839 if classname == "None":
840 pass
841 else:
842 if classes_ancestor.has_key(classname):
843 txt.write("\n\nClass %s(%s)\n" % (classname,
844 classes_ancestor[classname]))
845 classes.write("class %s(%s):\n" % (classname,
846 classes_ancestor[classname]))
847 classes.write(" def __init__(self, _obj=None):\n")
848 classes.write(" self._o = None\n")
849 classes.write(" %s.__init__(self, _obj=_obj)\n\n" % (
850 classes_ancestor[classname]))
851 if classes_ancestor[classname] == "xmlCore" or \
852 classes_ancestor[classname] == "xmlNode":
853 classes.write(" def __repr__(self):\n")
854 format = "%s:%%s" % (classname)
855 classes.write(" return \"%s\" %% (self.name)\n\n" % (
856 format))
857 else:
858 txt.write("Class %s()\n" % (classname))
859 classes.write("class %s:\n" % (classname))
860 classes.write(" def __init__(self, _obj=None):\n")
861 classes.write(" if _obj != None:self._o = _obj;return\n")
862 classes.write(" self._o = None\n\n");
863 if classes_destructors.has_key(classname):
864 classes.write(" def __del__(self):\n")
865 if classes_destructors[classname] == "pass":
866 classes.write(" pass\n")
867 else:
868 classes.write(" if self._o != None:\n")
869 classes.write(" libxsltmod.%s(self._o)\n" %
870 classes_destructors[classname]);
871 classes.write(" self._o = None\n\n");
872 flist = function_classes[classname]
873 flist.sort(functionCompare)
874 oldfile = ""
875 for info in flist:
876 (index, func, name, ret, args, file) = info
877 if file != oldfile:
878 if file == "python_accessor":
879 classes.write(" # accessors for %s\n" % (classname))
880 txt.write(" # accessors\n")
881 else:
882 classes.write(" #\n")
883 classes.write(" # %s functions from module %s\n" % (
884 classname, file))
885 txt.write("\n # functions from module %s\n" % file)
886 classes.write(" #\n\n")
887 oldfile = file
888 classes.write(" def %s(self" % func)
889 txt.write(" %s()\n" % func);
890 n = 0
891 for arg in args:
892 if n != index:
893 classes.write(", %s" % arg[0])
894 n = n + 1
895 classes.write("):\n")
896 writeDoc(name, args, ' ', classes);
897 n = 0
898 for arg in args:
899 if classes_type.has_key(arg[1]):
900 if n != index:
901 classes.write(" if %s == None: %s__o = None\n" %
902 (arg[0], arg[0]))
903 classes.write(" else: %s__o = %s%s\n" %
904 (arg[0], arg[0], classes_type[arg[1]][0]))
905 elif libxml2_classes_type.has_key(arg[1]):
906 classes.write(" if %s == None: %s__o = None\n" %
907 (arg[0], arg[0]))
908 classes.write(" else: %s__o = %s%s\n" %
909 (arg[0], arg[0],
910 libxml2_classes_type[arg[1]][0]))
911 n = n + 1
912 if ret[0] != "void":
913 classes.write(" ret = ");
914 else:
915 classes.write(" ");
916 classes.write("libxsltmod.%s(" % name)
917 n = 0
918 for arg in args:
919 if n != 0:
920 classes.write(", ");
921 if n != index:
922 classes.write("%s" % arg[0])
923 if classes_type.has_key(arg[1]):
924 classes.write("__o");
925 elif libxml2_classes_type.has_key(arg[1]):
926 classes.write("__o");
927 else:
928 classes.write("self");
929 if classes_type.has_key(arg[1]):
930 classes.write(classes_type[arg[1]][0])
931 elif libxml2_classes_type.has_key(arg[1]):
932 classes.write(libxml2_classes_type[arg[1]][0])
933 n = n + 1
934 classes.write(")\n");
935 if ret[0] != "void":
936 if classes_type.has_key(ret[0]):
937 classes.write(" if ret == None: return None\n");
938 classes.write(" return ");
939 classes.write(classes_type[ret[0]][1] % ("ret"));
940 classes.write("\n");
941 elif libxml2_classes_type.has_key(ret[0]):
942 classes.write(" if ret == None: return None\n");
943 classes.write(" return libxml2.");
944 classes.write(libxml2_classes_type[ret[0]][1] % ("ret"));
945 classes.write("\n");
946 elif converter_type.has_key(ret[0]):
947 classes.write(" if ret == None: return None\n");
948 classes.write(" return ");
949 classes.write(converter_type[ret[0]] % ("ret"));
950 classes.write("\n");
951 else:
952 classes.write(" return ret\n");
953 classes.write("\n");
954
955 #
956 # Generate enum constants
957 #
958 for type,enum in enums.items():
959 classes.write("# %s\n" % type)
960 items = enum.items()
961 items.sort(lambda i1,i2: cmp(long(i1[1]),long(i2[1])))
962 for name,value in items:
963 classes.write("%s = %s\n" % (name,value))
964 classes.write("\n");
965
966 txt.close()
967 classes.close()
968
969buildStubs()
970buildWrappers()
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette