BindingsGenerator.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import CppHeaderParser
  2. import ConfigParser
  3. import io
  4. import os
  5. import re
  6. from LuaBindingsGenerator import *
  7. from JSBindingsGenerator import *
  8. class BindingsGenerator(object):
  9. def __init__(self, engines, configFile):
  10. self.config = ConfigParser.RawConfigParser(allow_no_value=True)
  11. self.config.read(configFile)
  12. self.targetDir = self.config.get('global', 'TargetDirectory')
  13. self.ignoreFiles = self.config.get('global', 'IgnoreFiles')
  14. self.symbolsToStrip = self.config.get('global', 'StripSymbols').replace(" ", "").split(",")
  15. self.ignoreClasses = self.config.get('global', 'IgnoreClasses').replace(" ", "").split(",")
  16. self.ignoreMethods = self.config.get('global', 'IgnoreMethods').replace(" ", "").split(",")
  17. self.engines = {LuaBindingsGenerator(self.config), JSBindingsGenerator(self.config)}
  18. # ----------------------------------------------------
  19. # Utility methods
  20. # ----------------------------------------------------
  21. def error(self, msg):
  22. print("\033[91mERROR: %s" % (msg))
  23. print("\033[0m")
  24. # ----------------------------------------------------
  25. # Interface methods called in bindings engines
  26. # ----------------------------------------------------
  27. def processTargetFile(self, targetFile):
  28. for e in self.engines:
  29. e.processTargetFile(targetFile)
  30. def processClass(self, c):
  31. for e in self.engines:
  32. e.processClass(c)
  33. def finalize(self):
  34. for e in self.engines:
  35. e.finalize()
  36. # ----------------------------------------------------
  37. # Clean up doxygen stuff out of comment docs
  38. # ----------------------------------------------------
  39. def cleanDocs(self, docs):
  40. return docs.replace("/*", "").replace("*/", "").replace("*", "").replace("\n", "").replace("\r", "").replace("::", ".").replace("\t", "")
  41. # ----------------------------------------------------
  42. # Clean and reduce types to standard identifiers
  43. # ----------------------------------------------------
  44. def typeFilter(self, ty):
  45. ty = ty.replace("Polycode::", "")
  46. ty = ty.replace("std::", "")
  47. ty = ty.replace("const", "")
  48. ty = ty.replace("inline", "")
  49. ty = ty.replace("static", "")
  50. ty = ty.replace("virtual", "")
  51. ty = ty.replace("&", "")
  52. ty = re.sub(r'^.*\sint\s*$', 'int', ty) # eg "unsigned int"
  53. ty = re.sub(r'^.*\schar\s*$', 'char', ty) # eg "unsigned int"
  54. ty = re.sub(r'^.*\slong\s*$', 'int', ty)
  55. ty = re.sub(r'^.*\swchar_t\s*$', 'int', ty)
  56. ty = re.sub(r'^.*\sshort\s*$', 'int', ty)
  57. ty = re.sub(r'^.*\sfloat\s*$', 'Number', ty)
  58. ty = re.sub(r'^.*\sdouble\s*$', 'Number', ty) # eg "long double"
  59. ty = ty.replace("unsigned", "int")
  60. ty = ty.replace("long", "int")
  61. ty = ty.replace("float", "Number")
  62. ty = ty.replace("double", "Number")
  63. ty = ty.replace(" ", "") # Not very safe!
  64. return ty
  65. # ----------------------------------------------------
  66. # Parse and clean properties from a class
  67. # ----------------------------------------------------
  68. def parseClassProperties(self, c):
  69. properties = []
  70. for pp in c["properties"]["public"]:
  71. classPP = {}
  72. classPP["name"] = pp["name"]
  73. pp["type"] = pp["type"].replace("Polycode::", "")
  74. pp["type"] = pp["type"].replace("std::", "")
  75. classPP["type"] = self.typeFilter(pp["type"])
  76. if pp["type"].find("POLYIGNORE") != -1:
  77. continue
  78. if pp["name"] == "" or pp["array"] == 1:
  79. continue
  80. if "::union" in pp["name"]:
  81. continue
  82. if pp["type"].replace("*", "") in self.ignoreClasses:
  83. continue
  84. if pp["type"].find("static ") != -1:
  85. classPP["isStatic"] = True
  86. if "defaltValue" in pp: #this is misspelled in parser library
  87. classPP["defaultValue"] = pp["defaltValue"]
  88. if 'doxygen' in pp:
  89. classPP["doc"] = self.cleanDocs(pp['doxygen'])
  90. properties.append(classPP)
  91. else:
  92. classPP["isStatic"] = False
  93. if pp["type"].find("vector") == -1 and pp["name"] != "setScale" and pp["name"] != "setPosition" and pp["name"] != "BUFFER_CACHE_PRECISION" and not pp["name"].isdigit():
  94. properties.append(classPP)
  95. return properties
  96. # ----------------------------------------------------
  97. # Parse and clean methods
  98. # ----------------------------------------------------
  99. def parseClassMethods(self, c):
  100. methods = []
  101. parsedMethods = []
  102. for pm in c["methods"]["public"]:
  103. method = {}
  104. method["name"] = pm["name"]
  105. if pm["rtnType"].find("static ") == -1:
  106. method["isStatic"] = False
  107. else:
  108. method["isStatic"] = True
  109. method["type"] = self.typeFilter(pm["rtnType"])
  110. if pm["name"] in parsedMethods or pm["name"].find("operator") > -1 or pm["rtnType"].find("POLYIGNORE") > -1 or pm["name"] in self.ignoreMethods :
  111. continue
  112. #ignore destructors
  113. if pm["name"] == "~"+c["name"]:
  114. continue
  115. method["parameters"] = []
  116. for param in pm["parameters"]:
  117. mParam = {}
  118. if not "name" in param:
  119. continue
  120. if not "type" in param:
  121. continue
  122. if param["type"] == "0":
  123. continue
  124. mParam["name"] = param["name"]
  125. mParam["type"] = self.typeFilter(param["type"])
  126. if "defaltValue" in param:
  127. mParam["defaultValue"] = param["defaltValue"]
  128. method["parameters"].append(mParam)
  129. parsedMethods.append(pm["name"])
  130. methods.append(method)
  131. return methods
  132. # ----------------------------------------------------
  133. # Parse and clean data from a class
  134. # ----------------------------------------------------
  135. def parseClassData(self, c, ckey):
  136. classData = {}
  137. classData["name"] = ckey
  138. if len(c["inherits"]) > 0:
  139. if c["inherits"][0]["class"] not in self.ignoreClasses:
  140. classData["parent"] = c["inherits"][0]["class"]
  141. if 'doxygen' in c:
  142. classData["doc"] = self.cleanDocs(c['doxygen'])
  143. properties = self.parseClassProperties(c)
  144. classData["properties"] = []
  145. classData["staticProperties"] = []
  146. for p in properties:
  147. if p["isStatic"] == True:
  148. classData["staticProperties"].append(p)
  149. else:
  150. classData["properties"].append(p)
  151. classData["methods"] = self.parseClassMethods(c)
  152. return classData
  153. # ----------------------------------------------------
  154. # Parse files and create bindings
  155. # ----------------------------------------------------
  156. def createBindings(self):
  157. print("\nPolycode bindings generator v0.1\n")
  158. print("\033[93mGenerating bindings...")
  159. print("\033[93mParsing files from \033[92m[%s]" % (self.targetDir))
  160. if not os.path.isdir(self.targetDir):
  161. self.error("Target directory not valid!")
  162. return
  163. files = os.listdir(self.targetDir)
  164. filteredFiles = []
  165. for fileName in files:
  166. fileName = "%s/%s" % (self.targetDir, fileName)
  167. if os.path.isdir(fileName):
  168. continue
  169. head, tail = os.path.split(fileName)
  170. ignore = self.ignoreFiles.replace(" ", "").split(",")
  171. if tail.split(".")[1] == "h" and tail.split(".")[0] not in ignore:
  172. filteredFiles.append(fileName)
  173. self.processTargetFile(tail)
  174. for fileName in filteredFiles:
  175. try:
  176. f = open(fileName)
  177. contents = f.read()
  178. for s in self.symbolsToStrip:
  179. contents = contents.replace(s, "")
  180. cppHeader = CppHeaderParser.CppHeader(contents, "string")
  181. for ckey in cppHeader.classes:
  182. if ckey in self.ignoreClasses:
  183. continue
  184. if "::union" in ckey:
  185. continue
  186. print("\033[93mParsing class \033[0m[\033[92m%s\033[0m]" % ckey)
  187. c = cppHeader.classes[ckey]
  188. classData = self.parseClassData(c, ckey)
  189. self.processClass(classData)
  190. except CppHeaderParser.CppParseError as e:
  191. self.error(e)
  192. return
  193. self.finalize()