1#!/usr/bin/env python3 2# 3# generate python wrappers from the XML API description 4# 5 6functions = {} 7enums = {} # { enumType: { enumConstant: enumValue } } 8 9import os 10import sys 11import string 12 13if __name__ == "__main__": 14 # launched as a script 15 srcPref = os.path.dirname(sys.argv[0]) 16else: 17 # imported 18 srcPref = os.path.dirname(__file__) 19 20####################################################################### 21# 22# That part if purely the API acquisition phase from the 23# XML API description 24# 25####################################################################### 26import os 27import xml.sax 28 29debug = 0 30 31def getparser(): 32 # Attach parser to an unmarshalling object. return both objects. 33 target = docParser() 34 parser = xml.sax.make_parser() 35 parser.setContentHandler(target) 36 return parser, target 37 38class docParser(xml.sax.handler.ContentHandler): 39 def __init__(self): 40 self._methodname = None 41 self._data = [] 42 self.in_function = 0 43 44 self.startElement = self.start 45 self.endElement = self.end 46 self.characters = self.data 47 48 def close(self): 49 if debug: 50 print("close") 51 52 def getmethodname(self): 53 return self._methodname 54 55 def data(self, text): 56 if debug: 57 print("data %s" % text) 58 self._data.append(text) 59 60 def start(self, tag, attrs): 61 if debug: 62 print("start %s, %s" % (tag, attrs)) 63 if tag == 'function': 64 self._data = [] 65 self.in_function = 1 66 self.function = None 67 self.function_cond = None 68 self.function_args = [] 69 self.function_descr = None 70 self.function_return = None 71 self.function_file = None 72 if 'name' in attrs.keys(): 73 self.function = attrs['name'] 74 if 'file' in attrs.keys(): 75 self.function_file = attrs['file'] 76 elif tag == 'cond': 77 self._data = [] 78 elif tag == 'info': 79 self._data = [] 80 elif tag == 'arg': 81 if self.in_function == 1: 82 self.function_arg_name = None 83 self.function_arg_type = None 84 self.function_arg_info = None 85 if 'name' in attrs.keys(): 86 self.function_arg_name = attrs['name'] 87 if 'type' in attrs.keys(): 88 self.function_arg_type = attrs['type'] 89 if 'info' in attrs.keys(): 90 self.function_arg_info = attrs['info'] 91 elif tag == 'return': 92 if self.in_function == 1: 93 self.function_return_type = None 94 self.function_return_info = None 95 self.function_return_field = None 96 if 'type' in attrs.keys(): 97 self.function_return_type = attrs['type'] 98 if 'info' in attrs.keys(): 99 self.function_return_info = attrs['info'] 100 if 'field' in attrs.keys(): 101 self.function_return_field = attrs['field'] 102 elif tag == 'enum': 103 enum(attrs['type'],attrs['name'],attrs['value']) 104 105 def end(self, tag): 106 if debug: 107 print("end %s" % tag) 108 if tag == 'function': 109 if self.function != None: 110 function(self.function, self.function_descr, 111 self.function_return, self.function_args, 112 self.function_file, self.function_cond) 113 self.in_function = 0 114 elif tag == 'arg': 115 if self.in_function == 1: 116 self.function_args.append([self.function_arg_name, 117 self.function_arg_type, 118 self.function_arg_info]) 119 elif tag == 'return': 120 if self.in_function == 1: 121 self.function_return = [self.function_return_type, 122 self.function_return_info, 123 self.function_return_field] 124 elif tag == 'info': 125 str = '' 126 for c in self._data: 127 str = str + c 128 if self.in_function == 1: 129 self.function_descr = str 130 elif tag == 'cond': 131 str = '' 132 for c in self._data: 133 str = str + c 134 if self.in_function == 1: 135 self.function_cond = str 136 137 138def function(name, desc, ret, args, file, cond): 139 functions[name] = (desc, ret, args, file, cond) 140 141def enum(type, name, value): 142 if type not in enums: 143 enums[type] = {} 144 enums[type][name] = value 145 146####################################################################### 147# 148# Some filtering rukes to drop functions/types which should not 149# be exposed as-is on the Python interface 150# 151####################################################################### 152 153skipped_modules = { 154 'xmlmemory': None, 155 'SAX': None, 156 'hash': None, 157 'list': None, 158 'threads': None, 159# 'xpointer': None, 160} 161skipped_types = { 162 'int *': "usually a return type", 163 'xmlSAXHandlerPtr': "not the proper interface for SAX", 164 'htmlSAXHandlerPtr': "not the proper interface for SAX", 165 'xmlRMutexPtr': "thread specific, skipped", 166 'xmlMutexPtr': "thread specific, skipped", 167 'xmlGlobalStatePtr': "thread specific, skipped", 168 'xmlListPtr': "internal representation not suitable for python", 169 'xmlBufferPtr': "internal representation not suitable for python", 170 'FILE *': None, 171} 172 173####################################################################### 174# 175# Table of remapping to/from the python type or class to the C 176# counterpart. 177# 178####################################################################### 179 180py_types = { 181 'void': (None, None, None, None), 182 'int': ('i', None, "int", "int"), 183 'long': ('l', None, "long", "long"), 184 'double': ('d', None, "double", "double"), 185 'unsigned int': ('i', None, "int", "int"), 186 'xmlChar': ('c', None, "int", "int"), 187 'unsigned char *': ('z', None, "charPtr", "char *"), 188 'char *': ('z', None, "charPtr", "char *"), 189 'const char *': ('z', None, "charPtrConst", "const char *"), 190 'xmlChar *': ('z', None, "xmlCharPtr", "xmlChar *"), 191 'const xmlChar *': ('z', None, "xmlCharPtrConst", "const xmlChar *"), 192 'xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 193 'const xmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 194 'xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 195 'const xmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 196 'xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 197 'const xmlDtdPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 198 'xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 199 'const xmlDtd *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 200 'xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 201 'const xmlAttrPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 202 'xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 203 'const xmlAttr *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 204 'xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 205 'const xmlEntityPtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 206 'xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 207 'const xmlEntity *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 208 'xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"), 209 'const xmlElementPtr': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"), 210 'xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"), 211 'const xmlElement *': ('O', "xmlElement", "xmlElementPtr", "xmlElementPtr"), 212 'xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"), 213 'const xmlAttributePtr': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"), 214 'xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"), 215 'const xmlAttribute *': ('O', "xmlAttribute", "xmlAttributePtr", "xmlAttributePtr"), 216 'xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"), 217 'const xmlNsPtr': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"), 218 'xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"), 219 'const xmlNs *': ('O', "xmlNode", "xmlNsPtr", "xmlNsPtr"), 220 'xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 221 'const xmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 222 'xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 223 'const xmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 224 'htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 225 'const htmlDocPtr': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 226 'htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 227 'const htmlDoc *': ('O', "xmlNode", "xmlDocPtr", "xmlDocPtr"), 228 'htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 229 'const htmlNodePtr': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 230 'htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 231 'const htmlNode *': ('O', "xmlNode", "xmlNodePtr", "xmlNodePtr"), 232 'xmlXPathContextPtr': ('O', "xmlXPathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"), 233 'xmlXPathContext *': ('O', "xpathContext", "xmlXPathContextPtr", "xmlXPathContextPtr"), 234 'xmlXPathParserContextPtr': ('O', "xmlXPathParserContext", "xmlXPathParserContextPtr", "xmlXPathParserContextPtr"), 235 'xmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"), 236 'xmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"), 237 'htmlParserCtxtPtr': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"), 238 'htmlParserCtxt *': ('O', "parserCtxt", "xmlParserCtxtPtr", "xmlParserCtxtPtr"), 239 'xmlValidCtxtPtr': ('O', "ValidCtxt", "xmlValidCtxtPtr", "xmlValidCtxtPtr"), 240 'xmlCatalogPtr': ('O', "catalog", "xmlCatalogPtr", "xmlCatalogPtr"), 241 'FILE *': ('O', "File", "FILEPtr", "FILE *"), 242 'xmlURIPtr': ('O', "URI", "xmlURIPtr", "xmlURIPtr"), 243 'const xmlError *': ('O', "Error", "xmlErrorPtr", "const xmlError *"), 244 'xmlErrorPtr': ('O', "Error", "xmlErrorPtr", "xmlErrorPtr"), 245 'xmlOutputBufferPtr': ('O', "outputBuffer", "xmlOutputBufferPtr", "xmlOutputBufferPtr"), 246 'xmlParserInputBufferPtr': ('O', "inputBuffer", "xmlParserInputBufferPtr", "xmlParserInputBufferPtr"), 247 'xmlRegexpPtr': ('O', "xmlReg", "xmlRegexpPtr", "xmlRegexpPtr"), 248 'xmlTextReaderLocatorPtr': ('O', "xmlTextReaderLocator", "xmlTextReaderLocatorPtr", "xmlTextReaderLocatorPtr"), 249 'xmlTextReaderPtr': ('O', "xmlTextReader", "xmlTextReaderPtr", "xmlTextReaderPtr"), 250 'xmlRelaxNGPtr': ('O', "relaxNgSchema", "xmlRelaxNGPtr", "xmlRelaxNGPtr"), 251 'xmlRelaxNGParserCtxtPtr': ('O', "relaxNgParserCtxt", "xmlRelaxNGParserCtxtPtr", "xmlRelaxNGParserCtxtPtr"), 252 'xmlRelaxNGValidCtxtPtr': ('O', "relaxNgValidCtxt", "xmlRelaxNGValidCtxtPtr", "xmlRelaxNGValidCtxtPtr"), 253 'xmlSchemaPtr': ('O', "Schema", "xmlSchemaPtr", "xmlSchemaPtr"), 254 'xmlSchemaParserCtxtPtr': ('O', "SchemaParserCtxt", "xmlSchemaParserCtxtPtr", "xmlSchemaParserCtxtPtr"), 255 'xmlSchemaValidCtxtPtr': ('O', "SchemaValidCtxt", "xmlSchemaValidCtxtPtr", "xmlSchemaValidCtxtPtr"), 256} 257 258py_return_types = { 259 'xmlXPathObjectPtr': ('O', "foo", "xmlXPathObjectPtr", "xmlXPathObjectPtr"), 260} 261 262unknown_types = {} 263 264foreign_encoding_args = ( 265 'htmlCreateMemoryParserCtxt', 266 'htmlCtxtReadMemory', 267 'htmlParseChunk', 268 'htmlReadMemory', 269 'xmlCreateMemoryParserCtxt', 270 'xmlCtxtReadMemory', 271 'xmlCtxtResetPush', 272 'xmlParseChunk', 273 'xmlParseMemory', 274 'xmlReadMemory', 275 'xmlRecoverMemory', 276) 277 278####################################################################### 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 285# Class methods which are written by hand in libxml.c but the Python-level 286# code is still automatically generated (so they are not in skip_function()). 287skip_impl = ( 288 'xmlSaveFileTo', 289 'xmlSaveFormatFileTo', 290) 291 292deprecated_funcs = { 293 'htmlDefaultSAXHandlerInit': True, 294 'htmlHandleOmittedElem': True, 295 'htmlInitAutoClose': True, 296 'htmlParseCharRef': True, 297 'htmlParseElement': True, 298 'namePop': True, 299 'namePush': True, 300 'nodePop': True, 301 'nodePush': True, 302 'xmlCheckFilename': True, 303 'xmlCheckLanguageID': True, 304 'xmlCleanupCharEncodingHandlers': True, 305 'xmlCleanupGlobals': True, 306 'xmlDefaultSAXHandlerInit': True, 307 'xmlDecodeEntities': True, 308 'xmlDictCleanup': True, 309 'xmlEncodeEntities': True, 310 'xmlFileMatch': True, 311 'xmlGetCompressMode': True, 312 'xmlHandleEntity': True, 313 'xmlInitCharEncodingHandlers': True, 314 'xmlInitGlobals': True, 315 'xmlInitializeDict': True, 316 'xmlInitializePredefinedEntities': True, 317 'xmlIOFTPMatch': True, 318 'xmlIOHTTPMatch': True, 319 'xmlIsRef': True, 320 'xmlKeepBlanksDefault': True, 321 'xmlLineNumbersDefault': True, 322 'xmlNamespaceParseNCName': True, 323 'xmlNamespaceParseNSDef': True, 324 'xmlNanoFTPCleanup': True, 325 'xmlNanoFTPInit': True, 326 'xmlNanoFTPProxy': True, 327 'xmlNanoFTPScanProxy': True, 328 'xmlNanoHTTPCleanup': True, 329 'xmlNanoHTTPInit': True, 330 'xmlNanoHTTPScanProxy': True, 331 'xmlNewGlobalNs': True, 332 'xmlNextChar': True, 333 'xmlNormalizeWindowsPath': True, 334 'xmlParseAttValue': True, 335 'xmlParseAttributeListDecl': True, 336 'xmlParseCDSect': True, 337 'xmlParseCharData': True, 338 'xmlParseCharRef': True, 339 'xmlParseComment': True, 340 'xmlParseDocTypeDecl': True, 341 'xmlParseElement': True, 342 'xmlParseElementDecl': True, 343 'xmlParseEncName': True, 344 'xmlParseEncodingDecl': True, 345 'xmlParseEndTag': True, 346 'xmlParseEntity': True, 347 'xmlParseEntityDecl': True, 348 'xmlParseEntityRef': True, 349 'xmlParseMarkupDecl': True, 350 'xmlParseMisc': True, 351 'xmlParseName': True, 352 'xmlParseNamespace': True, 353 'xmlParseNmtoken': True, 354 'xmlParseNotationDecl': True, 355 'xmlParsePEReference': True, 356 'xmlParsePI': True, 357 'xmlParsePITarget': True, 358 'xmlParsePubidLiteral': True, 359 'xmlParseQuotedString': True, 360 'xmlParseReference': True, 361 'xmlParseSDDecl': True, 362 'xmlParseStartTag': True, 363 'xmlParseSystemLiteral': True, 364 'xmlParseTextDecl': True, 365 'xmlParseVersionInfo': True, 366 'xmlParseVersionNum': True, 367 'xmlParseXMLDecl': True, 368 'xmlParserHandlePEReference': True, 369 'xmlParserHandleReference': True, 370 'xmlParserSetLineNumbers': True, 371 'xmlParserSetLoadSubset': True, 372 'xmlParserSetPedantic': True, 373 'xmlParserSetReplaceEntities': True, 374 'xmlParserSetValidate': True, 375 'xmlPedanticParserDefault': True, 376 'xmlRecoverDoc': True, 377 'xmlRecoverFile': True, 378 'xmlRecoverMemory': True, 379 'xmlRegisterHTTPPostCallbacks': True, 380 'xmlRelaxNGCleanupTypes': True, 381 'xmlRelaxNGInitTypes': True, 382 'xmlRemoveRef': True, 383 'xmlSAXDefaultVersion': True, 384 'xmlScanName': True, 385 'xmlSchemaCleanupTypes': True, 386 'xmlSchemaInitTypes': True, 387 'xmlSetCompressMode': True, 388 'xmlSetupParserForBuffer': True, 389 'xmlSkipBlankChars': True, 390 'xmlStringDecodeEntities': True, 391 'xmlStringLenDecodeEntities': True, 392 'xmlSubstituteEntitiesDefault': True, 393 'xmlThrDefDefaultBufferSize': True, 394 'xmlThrDefDoValidityCheckingDefaultValue': True, 395 'xmlThrDefGetWarningsDefaultValue': True, 396 'xmlThrDefIndentTreeOutput': True, 397 'xmlThrDefKeepBlanksDefaultValue': True, 398 'xmlThrDefLineNumbersDefaultValue': True, 399 'xmlThrDefLoadExtDtdDefaultValue': True, 400 'xmlThrDefParserDebugEntities': True, 401 'xmlThrDefPedanticParserDefaultValue': True, 402 'xmlThrDefSaveNoEmptyTags': True, 403 'xmlThrDefSubstituteEntitiesDefaultValue': True, 404 'xmlThrDefTreeIndentString': True, 405 'xmlValidCtxtNormalizeAttributeValue': True, 406 'xmlValidNormalizeAttributeValue': True, 407 'xmlValidateAttributeValue': True, 408 'xmlValidateDocumentFinal': True, 409 'xmlValidateDtdFinal': True, 410 'xmlValidateNotationUse': True, 411 'xmlValidateOneAttribute': True, 412 'xmlValidateOneElement': True, 413 'xmlValidateOneNamespace': True, 414 'xmlValidatePopElement': True, 415 'xmlValidatePushCData': True, 416 'xmlValidatePushElement': True, 417 'xmlValidateRoot': True, 418 'xmlValidate': True, 419 'xmlXPathInit': True, 420 'xmlXPtrEvalRangePredicate': True, 421 'xmlXPtrNewCollapsedRange': True, 422 'xmlXPtrNewContext': True, 423 'xmlXPtrNewLocationSetNodes': True, 424 'xmlXPtrNewRange': True, 425 'xmlXPtrNewRangeNodes': True, 426 'xmlXPtrRangeToFunction': True, 427} 428 429def skip_function(name): 430 if name[0:12] == "xmlXPathWrap": 431 return 1 432 if name == "xmlFreeParserCtxt": 433 return 1 434 if name == "xmlCleanupParser": 435 return 1 436 if name == "xmlFreeTextReader": 437 return 1 438# if name[0:11] == "xmlXPathNew": 439# return 1 440 # the next function is defined in libxml.c 441 if name == "xmlRelaxNGFreeValidCtxt": 442 return 1 443 if name == "xmlFreeValidCtxt": 444 return 1 445 if name == "xmlSchemaFreeValidCtxt": 446 return 1 447 448# 449# Those are skipped because the Const version is used of the bindings 450# instead. 451# 452 if name == "xmlTextReaderBaseUri": 453 return 1 454 if name == "xmlTextReaderLocalName": 455 return 1 456 if name == "xmlTextReaderName": 457 return 1 458 if name == "xmlTextReaderNamespaceUri": 459 return 1 460 if name == "xmlTextReaderPrefix": 461 return 1 462 if name == "xmlTextReaderXmlLang": 463 return 1 464 if name == "xmlTextReaderValue": 465 return 1 466 if name == "xmlOutputBufferClose": # handled by by the superclass 467 return 1 468 if name == "xmlOutputBufferFlush": # handled by by the superclass 469 return 1 470 if name == "xmlErrMemory": 471 return 1 472 473 if name == "xmlValidBuildContentModel": 474 return 1 475 if name == "xmlValidateElementDecl": 476 return 1 477 if name == "xmlValidateAttributeDecl": 478 return 1 479 if name == "xmlPopInputCallbacks": 480 return 1 481 482 return 0 483 484def print_function_wrapper(name, output, export, include): 485 global py_types 486 global unknown_types 487 global functions 488 global skipped_modules 489 490 try: 491 (desc, ret, args, file, cond) = functions[name] 492 except: 493 print("failed to get function %s infos") 494 return 495 496 if file in skipped_modules: 497 return 0 498 if skip_function(name) == 1: 499 return 0 500 if name in skip_impl: 501 # Don't delete the function entry in the caller. 502 return 1 503 504 if name.startswith('xmlUCSIs'): 505 is_deprecated = name != 'xmlUCSIsBlock' and name != 'xmlUCSIsCat' 506 else: 507 is_deprecated = name in deprecated_funcs 508 509 c_call = "" 510 format="" 511 format_args="" 512 c_args="" 513 c_return="" 514 c_convert="" 515 c_release="" 516 num_bufs=0 517 for arg in args: 518 # This should be correct 519 if arg[1][0:6] == "const ": 520 arg[1] = arg[1][6:] 521 c_args = c_args + " %s %s;\n" % (arg[1], arg[0]) 522 if arg[1] in py_types: 523 (f, t, n, c) = py_types[arg[1]] 524 if (f == 'z') and (name in foreign_encoding_args) and (num_bufs == 0): 525 f = 's#' 526 if f != None: 527 format = format + f 528 if t != None: 529 format_args = format_args + ", &pyobj_%s" % (arg[0]) 530 c_args = c_args + " PyObject *pyobj_%s;\n" % (arg[0]) 531 c_convert = c_convert + \ 532 " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0], 533 arg[1], t, arg[0]) 534 else: 535 format_args = format_args + ", &%s" % (arg[0]) 536 if f == 's#': 537 format_args = format_args + ", &py_buffsize%d" % num_bufs 538 c_args = c_args + " Py_ssize_t py_buffsize%d;\n" % num_bufs 539 num_bufs = num_bufs + 1 540 if c_call != "": 541 c_call = c_call + ", " 542 c_call = c_call + "%s" % (arg[0]) 543 if t == "File": 544 c_release = c_release + \ 545 " PyFile_Release(%s);\n" % (arg[0]) 546 else: 547 if arg[1] in skipped_types: 548 return 0 549 if arg[1] in unknown_types: 550 lst = unknown_types[arg[1]] 551 lst.append(name) 552 else: 553 unknown_types[arg[1]] = [name] 554 return -1 555 if format != "": 556 format = format + ":%s" % (name) 557 558 if ret[0] == 'void': 559 if file == "python_accessor": 560 if args[1][1] == "char *" or args[1][1] == "xmlChar *": 561 c_call = "\n if (%s->%s != NULL) xmlFree(%s->%s);\n" % ( 562 args[0][0], args[1][0], args[0][0], args[1][0]) 563 c_call = c_call + " %s->%s = (%s)xmlStrdup((const xmlChar *)%s);\n" % (args[0][0], 564 args[1][0], args[1][1], args[1][0]) 565 else: 566 c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0], 567 args[1][0]) 568 else: 569 c_call = "\n %s(%s);\n" % (name, c_call) 570 ret_convert = " Py_INCREF(Py_None);\n return(Py_None);\n" 571 elif ret[0] in py_types: 572 (f, t, n, c) = py_types[ret[0]] 573 c_return = c_return + " %s c_retval;\n" % (ret[0]) 574 if file == "python_accessor" and ret[2] != None: 575 c_call = "\n c_retval = %s->%s;\n" % (args[0][0], ret[2]) 576 else: 577 c_call = "\n c_retval = %s(%s);\n" % (name, c_call) 578 ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c) 579 ret_convert = ret_convert + " return(py_retval);\n" 580 elif ret[0] in py_return_types: 581 (f, t, n, c) = py_return_types[ret[0]] 582 c_return = c_return + " %s c_retval;\n" % (ret[0]) 583 c_call = "\n c_retval = %s(%s);\n" % (name, c_call) 584 ret_convert = " py_retval = libxml_%sWrap((%s) c_retval);\n" % (n,c) 585 ret_convert = ret_convert + " return(py_retval);\n" 586 else: 587 if ret[0] in skipped_types: 588 return 0 589 if ret[0] in unknown_types: 590 lst = unknown_types[ret[0]] 591 lst.append(name) 592 else: 593 unknown_types[ret[0]] = [name] 594 return -1 595 596 if cond != None and cond != "": 597 include.write("#if %s\n" % cond) 598 export.write("#if %s\n" % cond) 599 output.write("#if %s\n" % cond) 600 601 include.write("PyObject * ") 602 include.write("libxml_%s(PyObject *self, PyObject *args);\n" % (name)) 603 604 export.write(" { (char *)\"%s\", libxml_%s, METH_VARARGS, NULL },\n" % 605 (name, name)) 606 607 if file == "python": 608 # Those have been manually generated 609 if cond != None and cond != "": 610 include.write("#endif\n") 611 export.write("#endif\n") 612 output.write("#endif\n") 613 return 1 614 if file == "python_accessor" and ret[0] != "void" and ret[2] is None: 615 # Those have been manually generated 616 if cond != None and cond != "": 617 include.write("#endif\n") 618 export.write("#endif\n") 619 output.write("#endif\n") 620 return 1 621 622 if is_deprecated: 623 output.write("XML_IGNORE_DEPRECATION_WARNINGS\n") 624 output.write("PyObject *\n") 625 output.write("libxml_%s(PyObject *self ATTRIBUTE_UNUSED," % (name)) 626 output.write(" PyObject *args") 627 if format == "": 628 output.write(" ATTRIBUTE_UNUSED") 629 output.write(") {\n") 630 if ret[0] != 'void': 631 output.write(" PyObject *py_retval;\n") 632 if c_return != "": 633 output.write(c_return) 634 if c_args != "": 635 output.write(c_args) 636 if is_deprecated: 637 output.write("\n if (libxml_deprecationWarning(\"%s\") == -1)\n" % 638 name) 639 output.write(" return(NULL);\n") 640 if format != "": 641 output.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" % 642 (format, format_args)) 643 output.write(" return(NULL);\n") 644 if c_convert != "": 645 output.write(c_convert) 646 647 output.write(c_call) 648 if c_release != "": 649 output.write(c_release) 650 output.write(ret_convert) 651 output.write("}\n") 652 if is_deprecated: 653 output.write("XML_POP_WARNINGS\n") 654 output.write("\n") 655 656 if cond != None and cond != "": 657 include.write("#endif /* %s */\n" % cond) 658 export.write("#endif /* %s */\n" % cond) 659 output.write("#endif /* %s */\n" % cond) 660 return 1 661 662def buildStubs(): 663 global py_types 664 global py_return_types 665 global unknown_types 666 667 try: 668 f = open(os.path.join(srcPref,"libxml2-api.xml")) 669 data = f.read() 670 (parser, target) = getparser() 671 parser.feed(data) 672 parser.close() 673 except IOError as msg: 674 try: 675 f = open(os.path.join(srcPref,"..","doc","libxml2-api.xml")) 676 data = f.read() 677 (parser, target) = getparser() 678 parser.feed(data) 679 parser.close() 680 except IOError as msg: 681 print(file, ":", msg) 682 sys.exit(1) 683 684 n = len(list(functions.keys())) 685 print("Found %d functions in libxml2-api.xml" % (n)) 686 687 py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject") 688 try: 689 f = open(os.path.join(srcPref,"libxml2-python-api.xml")) 690 data = f.read() 691 (parser, target) = getparser() 692 parser.feed(data) 693 parser.close() 694 except IOError as msg: 695 print(file, ":", msg) 696 697 698 print("Found %d functions in libxml2-python-api.xml" % ( 699 len(list(functions.keys())) - n)) 700 nb_wrap = 0 701 failed = 0 702 skipped = 0 703 704 include = open("libxml2-py.h", "w") 705 include.write("/* Generated */\n\n") 706 export = open("libxml2-export.c", "w") 707 export.write("/* Generated */\n\n") 708 wrapper = open("libxml2-py.c", "w") 709 wrapper.write("/* Generated */\n\n") 710 wrapper.write("#define PY_SSIZE_T_CLEAN\n") 711 wrapper.write("#include <Python.h>\n") 712 wrapper.write("#include <libxml/xmlversion.h>\n") 713 wrapper.write("#include <libxml/tree.h>\n") 714 wrapper.write("#include <libxml/xmlschemastypes.h>\n") 715 wrapper.write("#include \"libxml_wrap.h\"\n") 716 wrapper.write("#include \"libxml2-py.h\"\n\n") 717 for function in sorted(functions.keys()): 718 ret = print_function_wrapper(function, wrapper, export, include) 719 if ret < 0: 720 failed = failed + 1 721 del functions[function] 722 if ret == 0: 723 skipped = skipped + 1 724 del functions[function] 725 if ret == 1: 726 nb_wrap = nb_wrap + 1 727 include.close() 728 export.close() 729 wrapper.close() 730 731 print("Generated %d wrapper functions, %d failed, %d skipped" % (nb_wrap, 732 failed, skipped)) 733# print("Missing type converters: ") 734# for type in list(unknown_types.keys()): 735# print("%s:%d " % (type, len(unknown_types[type]))) 736# print() 737 738####################################################################### 739# 740# This part writes part of the Python front-end classes based on 741# mapping rules between types and classes and also based on function 742# renaming to get consistent function names at the Python level 743# 744####################################################################### 745 746# 747# The type automatically remapped to generated classes 748# 749classes_type = { 750 "xmlNodePtr": ("._o", "xmlNode(_obj=%s)", "xmlNode"), 751 "xmlNode *": ("._o", "xmlNode(_obj=%s)", "xmlNode"), 752 "xmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"), 753 "xmlDoc *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"), 754 "htmlDocPtr": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"), 755 "htmlxmlDocPtr *": ("._o", "xmlDoc(_obj=%s)", "xmlDoc"), 756 "xmlAttrPtr": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"), 757 "xmlAttr *": ("._o", "xmlAttr(_obj=%s)", "xmlAttr"), 758 "xmlNsPtr": ("._o", "xmlNs(_obj=%s)", "xmlNs"), 759 "xmlNs *": ("._o", "xmlNs(_obj=%s)", "xmlNs"), 760 "xmlDtdPtr": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"), 761 "xmlDtd *": ("._o", "xmlDtd(_obj=%s)", "xmlDtd"), 762 "xmlEntityPtr": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"), 763 "xmlEntity *": ("._o", "xmlEntity(_obj=%s)", "xmlEntity"), 764 "xmlElementPtr": ("._o", "xmlElement(_obj=%s)", "xmlElement"), 765 "xmlElement *": ("._o", "xmlElement(_obj=%s)", "xmlElement"), 766 "xmlAttributePtr": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"), 767 "xmlAttribute *": ("._o", "xmlAttribute(_obj=%s)", "xmlAttribute"), 768 "xmlXPathContextPtr": ("._o", "xpathContext(_obj=%s)", "xpathContext"), 769 "xmlXPathContext *": ("._o", "xpathContext(_obj=%s)", "xpathContext"), 770 "xmlXPathParserContext *": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"), 771 "xmlXPathParserContextPtr": ("._o", "xpathParserContext(_obj=%s)", "xpathParserContext"), 772 "xmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"), 773 "xmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"), 774 "htmlParserCtxtPtr": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"), 775 "htmlParserCtxt *": ("._o", "parserCtxt(_obj=%s)", "parserCtxt"), 776 "xmlValidCtxtPtr": ("._o", "ValidCtxt(_obj=%s)", "ValidCtxt"), 777 "xmlCatalogPtr": ("._o", "catalog(_obj=%s)", "catalog"), 778 "xmlURIPtr": ("._o", "URI(_obj=%s)", "URI"), 779 "const xmlError *": ("._o", "Error(_obj=%s)", "Error"), 780 "xmlErrorPtr": ("._o", "Error(_obj=%s)", "Error"), 781 "xmlOutputBufferPtr": ("._o", "outputBuffer(_obj=%s)", "outputBuffer"), 782 "xmlParserInputBufferPtr": ("._o", "inputBuffer(_obj=%s)", "inputBuffer"), 783 "xmlRegexpPtr": ("._o", "xmlReg(_obj=%s)", "xmlReg"), 784 "xmlTextReaderLocatorPtr": ("._o", "xmlTextReaderLocator(_obj=%s)", "xmlTextReaderLocator"), 785 "xmlTextReaderPtr": ("._o", "xmlTextReader(_obj=%s)", "xmlTextReader"), 786 'xmlRelaxNGPtr': ('._o', "relaxNgSchema(_obj=%s)", "relaxNgSchema"), 787 'xmlRelaxNGParserCtxtPtr': ('._o', "relaxNgParserCtxt(_obj=%s)", "relaxNgParserCtxt"), 788 'xmlRelaxNGValidCtxtPtr': ('._o', "relaxNgValidCtxt(_obj=%s)", "relaxNgValidCtxt"), 789 'xmlSchemaPtr': ("._o", "Schema(_obj=%s)", "Schema"), 790 'xmlSchemaParserCtxtPtr': ("._o", "SchemaParserCtxt(_obj=%s)", "SchemaParserCtxt"), 791 'xmlSchemaValidCtxtPtr': ("._o", "SchemaValidCtxt(_obj=%s)", "SchemaValidCtxt"), 792} 793 794converter_type = { 795 "xmlXPathObjectPtr": "xpathObjectRet(%s)", 796} 797 798primary_classes = ["xmlNode", "xmlDoc"] 799 800classes_ancestor = { 801 "xmlNode" : "xmlCore", 802 "xmlDtd" : "xmlNode", 803 "xmlDoc" : "xmlNode", 804 "xmlAttr" : "xmlNode", 805 "xmlNs" : "xmlNode", 806 "xmlEntity" : "xmlNode", 807 "xmlElement" : "xmlNode", 808 "xmlAttribute" : "xmlNode", 809 "outputBuffer": "ioWriteWrapper", 810 "inputBuffer": "ioReadWrapper", 811 "parserCtxt": "parserCtxtCore", 812 "xmlTextReader": "xmlTextReaderCore", 813 "ValidCtxt": "ValidCtxtCore", 814 "SchemaValidCtxt": "SchemaValidCtxtCore", 815 "relaxNgValidCtxt": "relaxNgValidCtxtCore", 816} 817classes_destructors = { 818 "parserCtxt": "xmlFreeParserCtxt", 819 "catalog": "xmlFreeCatalog", 820 "URI": "xmlFreeURI", 821# "outputBuffer": "xmlOutputBufferClose", 822 "inputBuffer": "xmlFreeParserInputBuffer", 823 "xmlReg": "xmlRegFreeRegexp", 824 "xmlTextReader": "xmlFreeTextReader", 825 "relaxNgSchema": "xmlRelaxNGFree", 826 "relaxNgParserCtxt": "xmlRelaxNGFreeParserCtxt", 827 "relaxNgValidCtxt": "xmlRelaxNGFreeValidCtxt", 828 "Schema": "xmlSchemaFree", 829 "SchemaParserCtxt": "xmlSchemaFreeParserCtxt", 830 "SchemaValidCtxt": "xmlSchemaFreeValidCtxt", 831 "ValidCtxt": "xmlFreeValidCtxt", 832} 833 834functions_noexcept = { 835 "xmlHasProp": 1, 836 "xmlHasNsProp": 1, 837 "xmlDocSetRootElement": 1, 838 "xmlNodeGetNs": 1, 839 "xmlNodeGetNsDefs": 1, 840 "xmlNextElementSibling": 1, 841 "xmlPreviousElementSibling": 1, 842 "xmlFirstElementChild": 1, 843 "xmlLastElementChild": 1, 844} 845 846reference_keepers = { 847 "xmlTextReader": [('inputBuffer', 'input')], 848 "relaxNgValidCtxt": [('relaxNgSchema', 'schema')], 849 "SchemaValidCtxt": [('Schema', 'schema')], 850} 851 852function_classes = {} 853 854function_classes["None"] = [] 855 856def nameFixup(name, classe, type, file): 857 listname = classe + "List" 858 ll = len(listname) 859 l = len(classe) 860 if name[0:l] == listname: 861 func = name[l:] 862 func = func[0:1].lower() + func[1:] 863 elif name[0:12] == "xmlParserGet" and file == "python_accessor": 864 func = name[12:] 865 func = func[0:1].lower() + func[1:] 866 elif name[0:12] == "xmlParserSet" and file == "python_accessor": 867 func = name[12:] 868 func = func[0:1].lower() + func[1:] 869 elif name[0:10] == "xmlNodeGet" and file == "python_accessor": 870 func = name[10:] 871 func = func[0:1].lower() + func[1:] 872 elif name[0:9] == "xmlURIGet" and file == "python_accessor": 873 func = name[9:] 874 func = func[0:1].lower() + func[1:] 875 elif name[0:9] == "xmlURISet" and file == "python_accessor": 876 func = name[6:] 877 func = func[0:1].lower() + func[1:] 878 elif name[0:11] == "xmlErrorGet" and file == "python_accessor": 879 func = name[11:] 880 func = func[0:1].lower() + func[1:] 881 elif name[0:17] == "xmlXPathParserGet" and file == "python_accessor": 882 func = name[17:] 883 func = func[0:1].lower() + func[1:] 884 elif name[0:11] == "xmlXPathGet" and file == "python_accessor": 885 func = name[11:] 886 func = func[0:1].lower() + func[1:] 887 elif name[0:11] == "xmlXPathSet" and file == "python_accessor": 888 func = name[8:] 889 func = func[0:1].lower() + func[1:] 890 elif name[0:15] == "xmlOutputBuffer" and file != "python": 891 func = name[15:] 892 func = func[0:1].lower() + func[1:] 893 elif name[0:20] == "xmlParserInputBuffer" and file != "python": 894 func = name[20:] 895 func = func[0:1].lower() + func[1:] 896 elif name[0:9] == "xmlRegexp" and file == "xmlregexp": 897 func = "regexp" + name[9:] 898 elif name[0:6] == "xmlReg" and file == "xmlregexp": 899 func = "regexp" + name[6:] 900 elif name[0:20] == "xmlTextReaderLocator" and file == "xmlreader": 901 func = name[20:] 902 elif name[0:18] == "xmlTextReaderConst" and file == "xmlreader": 903 func = name[18:] 904 elif name[0:13] == "xmlTextReader" and file == "xmlreader": 905 func = name[13:] 906 elif name[0:12] == "xmlReaderNew" and file == "xmlreader": 907 func = name[9:] 908 elif name[0:11] == "xmlACatalog": 909 func = name[11:] 910 func = func[0:1].lower() + func[1:] 911 elif name[0:l] == classe: 912 func = name[l:] 913 func = func[0:1].lower() + func[1:] 914 elif name[0:7] == "libxml_": 915 func = name[7:] 916 func = func[0:1].lower() + func[1:] 917 elif name[0:6] == "xmlGet": 918 func = name[6:] 919 func = func[0:1].lower() + func[1:] 920 elif name[0:3] == "xml": 921 func = name[3:] 922 func = func[0:1].lower() + func[1:] 923 else: 924 func = name 925 if func[0:5] == "xPath": 926 func = "xpath" + func[5:] 927 elif func[0:4] == "xPtr": 928 func = "xpointer" + func[4:] 929 elif func[0:8] == "xInclude": 930 func = "xinclude" + func[8:] 931 elif func[0:2] == "iD": 932 func = "ID" + func[2:] 933 elif func[0:3] == "uRI": 934 func = "URI" + func[3:] 935 elif func[0:4] == "uTF8": 936 func = "UTF8" + func[4:] 937 elif func[0:3] == 'sAX': 938 func = "SAX" + func[3:] 939 return func 940 941 942def functionCompare(info1, info2): 943 (index1, func1, name1, ret1, args1, file1) = info1 944 (index2, func2, name2, ret2, args2, file2) = info2 945 if file1 == file2: 946 if func1 < func2: 947 return -1 948 if func1 > func2: 949 return 1 950 if file1 == "python_accessor": 951 return -1 952 if file2 == "python_accessor": 953 return 1 954 if file1 < file2: 955 return -1 956 if file1 > file2: 957 return 1 958 return 0 959 960def cmp_to_key(mycmp): 961 'Convert a cmp= function into a key= function' 962 class K(object): 963 def __init__(self, obj, *args): 964 self.obj = obj 965 def __lt__(self, other): 966 return mycmp(self.obj, other.obj) < 0 967 def __gt__(self, other): 968 return mycmp(self.obj, other.obj) > 0 969 def __eq__(self, other): 970 return mycmp(self.obj, other.obj) == 0 971 def __le__(self, other): 972 return mycmp(self.obj, other.obj) <= 0 973 def __ge__(self, other): 974 return mycmp(self.obj, other.obj) >= 0 975 def __ne__(self, other): 976 return mycmp(self.obj, other.obj) != 0 977 return K 978def writeDoc(name, args, indent, output): 979 if functions[name][0] is None or functions[name][0] == "": 980 return 981 val = functions[name][0] 982 val = val.replace("NULL", "None") 983 output.write(indent) 984 output.write('"""') 985 while len(val) > 60: 986 if val[0] == " ": 987 val = val[1:] 988 continue 989 str = val[0:60] 990 i = str.rfind(" ") 991 if i < 0: 992 i = 60 993 str = val[0:i] 994 val = val[i:] 995 output.write(str) 996 output.write('\n ') 997 output.write(indent) 998 output.write(val) 999 output.write(' """\n') 1000 1001def buildWrappers(): 1002 global ctypes 1003 global py_types 1004 global py_return_types 1005 global unknown_types 1006 global functions 1007 global function_classes 1008 global classes_type 1009 global classes_list 1010 global converter_type 1011 global primary_classes 1012 global converter_type 1013 global classes_ancestor 1014 global converter_type 1015 global primary_classes 1016 global classes_ancestor 1017 global classes_destructors 1018 global functions_noexcept 1019 1020 for type in classes_type.keys(): 1021 function_classes[classes_type[type][2]] = [] 1022 1023 # 1024 # Build the list of C types to look for ordered to start 1025 # with primary classes 1026 # 1027 ctypes = [] 1028 classes_list = [] 1029 ctypes_processed = {} 1030 classes_processed = {} 1031 for classe in primary_classes: 1032 classes_list.append(classe) 1033 classes_processed[classe] = () 1034 for type in classes_type.keys(): 1035 tinfo = classes_type[type] 1036 if tinfo[2] == classe: 1037 ctypes.append(type) 1038 ctypes_processed[type] = () 1039 for type in sorted(classes_type.keys()): 1040 if type in ctypes_processed: 1041 continue 1042 tinfo = classes_type[type] 1043 if tinfo[2] not in classes_processed: 1044 classes_list.append(tinfo[2]) 1045 classes_processed[tinfo[2]] = () 1046 1047 ctypes.append(type) 1048 ctypes_processed[type] = () 1049 1050 for name in functions.keys(): 1051 found = 0 1052 (desc, ret, args, file, cond) = functions[name] 1053 for type in ctypes: 1054 classe = classes_type[type][2] 1055 1056 if name[0:3] == "xml" and len(args) >= 1 and args[0][1] == type: 1057 found = 1 1058 func = nameFixup(name, classe, type, file) 1059 info = (0, func, name, ret, args, file) 1060 function_classes[classe].append(info) 1061 elif name[0:3] == "xml" and len(args) >= 2 and args[1][1] == type \ 1062 and file != "python_accessor": 1063 found = 1 1064 func = nameFixup(name, classe, type, file) 1065 info = (1, func, name, ret, args, file) 1066 function_classes[classe].append(info) 1067 elif name[0:4] == "html" and len(args) >= 1 and args[0][1] == type: 1068 found = 1 1069 func = nameFixup(name, classe, type, file) 1070 info = (0, func, name, ret, args, file) 1071 function_classes[classe].append(info) 1072 elif name[0:4] == "html" and len(args) >= 2 and args[1][1] == type \ 1073 and file != "python_accessor": 1074 found = 1 1075 func = nameFixup(name, classe, type, file) 1076 info = (1, func, name, ret, args, file) 1077 function_classes[classe].append(info) 1078 if found == 1: 1079 continue 1080 if name[0:8] == "xmlXPath": 1081 continue 1082 if name[0:6] == "xmlStr": 1083 continue 1084 if name[0:10] == "xmlCharStr": 1085 continue 1086 func = nameFixup(name, "None", file, file) 1087 info = (0, func, name, ret, args, file) 1088 function_classes['None'].append(info) 1089 1090 classes = open("libxml2class.py", "w") 1091 txt = open("libxml2class.txt", "w") 1092 txt.write(" Generated Classes for libxml2-python\n\n") 1093 1094 txt.write("#\n# Global functions of the module\n#\n\n") 1095 if "None" in function_classes: 1096 flist = function_classes["None"] 1097 flist = sorted(flist, key=cmp_to_key(functionCompare)) 1098 oldfile = "" 1099 for info in flist: 1100 (index, func, name, ret, args, file) = info 1101 if file != oldfile: 1102 classes.write("#\n# Functions from module %s\n#\n\n" % file) 1103 txt.write("\n# functions from module %s\n" % file) 1104 oldfile = file 1105 classes.write("def %s(" % func) 1106 txt.write("%s()\n" % func) 1107 n = 0 1108 for arg in args: 1109 if n != 0: 1110 classes.write(", ") 1111 classes.write("%s" % arg[0]) 1112 n = n + 1 1113 classes.write("):\n") 1114 writeDoc(name, args, ' ', classes) 1115 1116 for arg in args: 1117 if arg[1] in classes_type: 1118 classes.write(" if %s is None: %s__o = None\n" % 1119 (arg[0], arg[0])) 1120 classes.write(" else: %s__o = %s%s\n" % 1121 (arg[0], arg[0], classes_type[arg[1]][0])) 1122 if arg[1] in py_types: 1123 (f, t, n, c) = py_types[arg[1]] 1124 if t == "File": 1125 classes.write(" if %s is not None: %s.flush()\n" % ( 1126 arg[0], arg[0])) 1127 1128 if ret[0] != "void": 1129 classes.write(" ret = ") 1130 else: 1131 classes.write(" ") 1132 classes.write("libxml2mod.%s(" % name) 1133 n = 0 1134 for arg in args: 1135 if n != 0: 1136 classes.write(", ") 1137 classes.write("%s" % arg[0]) 1138 if arg[1] in classes_type: 1139 classes.write("__o") 1140 n = n + 1 1141 classes.write(")\n") 1142 1143# This may be needed to reposition the I/O, but likely to cause more harm 1144# than good. Those changes in Python3 really break the model. 1145# for arg in args: 1146# if arg[1] in py_types: 1147# (f, t, n, c) = py_types[arg[1]] 1148# if t == "File": 1149# classes.write(" if %s is not None: %s.seek(0,0)\n"%( 1150# arg[0], arg[0])) 1151 1152 if ret[0] != "void": 1153 if ret[0] in classes_type: 1154 # 1155 # Raise an exception 1156 # 1157 if name in functions_noexcept: 1158 classes.write(" if ret is None:return None\n") 1159 elif name.find("URI") >= 0: 1160 classes.write( 1161 " if ret is None:raise uriError('%s() failed')\n" 1162 % (name)) 1163 elif name.find("XPath") >= 0: 1164 classes.write( 1165 " if ret is None:raise xpathError('%s() failed')\n" 1166 % (name)) 1167 elif name.find("Parse") >= 0: 1168 classes.write( 1169 " if ret is None:raise parserError('%s() failed')\n" 1170 % (name)) 1171 else: 1172 classes.write( 1173 " if ret is None:raise treeError('%s() failed')\n" 1174 % (name)) 1175 classes.write(" return ") 1176 classes.write(classes_type[ret[0]][1] % ("ret")) 1177 classes.write("\n") 1178 else: 1179 classes.write(" return ret\n") 1180 classes.write("\n") 1181 1182 txt.write("\n\n#\n# Set of classes of the module\n#\n\n") 1183 for classname in classes_list: 1184 if classname == "None": 1185 pass 1186 else: 1187 if classname in classes_ancestor: 1188 txt.write("\n\nClass %s(%s)\n" % (classname, 1189 classes_ancestor[classname])) 1190 classes.write("class %s(%s):\n" % (classname, 1191 classes_ancestor[classname])) 1192 classes.write(" def __init__(self, _obj=None):\n") 1193 if classes_ancestor[classname] == "xmlCore" or \ 1194 classes_ancestor[classname] == "xmlNode": 1195 classes.write(" if checkWrapper(_obj) != 0:") 1196 classes.write(" raise TypeError") 1197 classes.write("('%s got a wrong wrapper object type')\n" % \ 1198 classname) 1199 if classname in reference_keepers: 1200 rlist = reference_keepers[classname] 1201 for ref in rlist: 1202 classes.write(" self.%s = None\n" % ref[1]) 1203 classes.write(" self._o = _obj\n") 1204 classes.write(" %s.__init__(self, _obj=_obj)\n\n" % ( 1205 classes_ancestor[classname])) 1206 if classes_ancestor[classname] == "xmlCore" or \ 1207 classes_ancestor[classname] == "xmlNode": 1208 classes.write(" def __repr__(self):\n") 1209 format = "<%s (%%s) object at 0x%%x>" % (classname) 1210 classes.write(" return \"%s\" %% (self.name, int(pos_id (self)))\n\n" % ( 1211 format)) 1212 else: 1213 txt.write("Class %s()\n" % (classname)) 1214 classes.write("class %s:\n" % (classname)) 1215 classes.write(" def __init__(self, _obj=None):\n") 1216 if classname in reference_keepers: 1217 list = reference_keepers[classname] 1218 for ref in list: 1219 classes.write(" self.%s = None\n" % ref[1]) 1220 classes.write(" if _obj != None:self._o = _obj;return\n") 1221 classes.write(" self._o = None\n\n") 1222 destruct=None 1223 if classname in classes_destructors: 1224 classes.write(" def __del__(self):\n") 1225 classes.write(" if self._o != None:\n") 1226 classes.write(" libxml2mod.%s(self._o)\n" % 1227 classes_destructors[classname]) 1228 classes.write(" self._o = None\n\n") 1229 destruct=classes_destructors[classname] 1230 flist = function_classes[classname] 1231 flist = sorted(flist, key=cmp_to_key(functionCompare)) 1232 oldfile = "" 1233 for info in flist: 1234 (index, func, name, ret, args, file) = info 1235 # 1236 # Do not provide as method the destructors for the class 1237 # to avoid double free 1238 # 1239 if name == destruct: 1240 continue 1241 if file != oldfile: 1242 if file == "python_accessor": 1243 classes.write(" # accessors for %s\n" % (classname)) 1244 txt.write(" # accessors\n") 1245 else: 1246 classes.write(" #\n") 1247 classes.write(" # %s functions from module %s\n" % ( 1248 classname, file)) 1249 txt.write("\n # functions from module %s\n" % file) 1250 classes.write(" #\n\n") 1251 oldfile = file 1252 classes.write(" def %s(self" % func) 1253 txt.write(" %s()\n" % func) 1254 n = 0 1255 for arg in args: 1256 if n != index: 1257 classes.write(", %s" % arg[0]) 1258 n = n + 1 1259 classes.write("):\n") 1260 writeDoc(name, args, ' ', classes) 1261 n = 0 1262 for arg in args: 1263 if arg[1] in classes_type: 1264 if n != index: 1265 classes.write(" if %s is None: %s__o = None\n" % 1266 (arg[0], arg[0])) 1267 classes.write(" else: %s__o = %s%s\n" % 1268 (arg[0], arg[0], classes_type[arg[1]][0])) 1269 n = n + 1 1270 if ret[0] != "void": 1271 classes.write(" ret = ") 1272 else: 1273 classes.write(" ") 1274 classes.write("libxml2mod.%s(" % name) 1275 n = 0 1276 for arg in args: 1277 if n != 0: 1278 classes.write(", ") 1279 if n != index: 1280 classes.write("%s" % arg[0]) 1281 if arg[1] in classes_type: 1282 classes.write("__o") 1283 else: 1284 classes.write("self") 1285 if arg[1] in classes_type: 1286 classes.write(classes_type[arg[1]][0]) 1287 n = n + 1 1288 classes.write(")\n") 1289 if ret[0] != "void": 1290 if ret[0] in classes_type: 1291 # 1292 # Raise an exception 1293 # 1294 if name in functions_noexcept: 1295 classes.write( 1296 " if ret is None:return None\n") 1297 elif name.find("URI") >= 0: 1298 classes.write( 1299 " if ret is None:raise uriError('%s() failed')\n" 1300 % (name)) 1301 elif name.find("XPath") >= 0: 1302 classes.write( 1303 " if ret is None:raise xpathError('%s() failed')\n" 1304 % (name)) 1305 elif name.find("Parse") >= 0: 1306 classes.write( 1307 " if ret is None:raise parserError('%s() failed')\n" 1308 % (name)) 1309 else: 1310 classes.write( 1311 " if ret is None:raise treeError('%s() failed')\n" 1312 % (name)) 1313 1314 # 1315 # generate the returned class wrapper for the object 1316 # 1317 classes.write(" __tmp = ") 1318 classes.write(classes_type[ret[0]][1] % ("ret")) 1319 classes.write("\n") 1320 1321 # 1322 # Sometime one need to keep references of the source 1323 # class in the returned class object. 1324 # See reference_keepers for the list 1325 # 1326 tclass = classes_type[ret[0]][2] 1327 if tclass in reference_keepers: 1328 list = reference_keepers[tclass] 1329 for pref in list: 1330 if pref[0] == classname: 1331 classes.write(" __tmp.%s = self\n" % 1332 pref[1]) 1333 # 1334 # return the class 1335 # 1336 classes.write(" return __tmp\n") 1337 elif ret[0] in converter_type: 1338 # 1339 # Raise an exception 1340 # 1341 if name in functions_noexcept: 1342 classes.write( 1343 " if ret is None:return None") 1344 elif name.find("URI") >= 0: 1345 classes.write( 1346 " if ret is None:raise uriError('%s() failed')\n" 1347 % (name)) 1348 elif name.find("XPath") >= 0: 1349 classes.write( 1350 " if ret is None:raise xpathError('%s() failed')\n" 1351 % (name)) 1352 elif name.find("Parse") >= 0: 1353 classes.write( 1354 " if ret is None:raise parserError('%s() failed')\n" 1355 % (name)) 1356 else: 1357 classes.write( 1358 " if ret is None:raise treeError('%s() failed')\n" 1359 % (name)) 1360 classes.write(" return ") 1361 classes.write(converter_type[ret[0]] % ("ret")) 1362 classes.write("\n") 1363 else: 1364 classes.write(" return ret\n") 1365 classes.write("\n") 1366 1367 # 1368 # Generate enum constants 1369 # 1370 for type,enum in enums.items(): 1371 classes.write("# %s\n" % type) 1372 items = enum.items() 1373 items = sorted(items, key=(lambda i: int(i[1]))) 1374 for name,value in items: 1375 classes.write("%s = %s\n" % (name,value)) 1376 classes.write("\n") 1377 1378 txt.close() 1379 classes.close() 1380 1381buildStubs() 1382buildWrappers() 1383