BindingsGenerator.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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, 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. # Clean and reduce types to standard identifiers
  67. # ----------------------------------------------------
  68. def cleanTypeFilter(self, ty):
  69. ty = ty.replace("shared_ptr", "")
  70. ty = ty.replace("<", "")
  71. ty = ty.replace(">", "")
  72. ty = ty.replace("*", "")
  73. return ty
  74. # ----------------------------------------------------
  75. # Parse and clean properties from a class
  76. # ----------------------------------------------------
  77. def parseClassProperties(self, c):
  78. properties = []
  79. for pp in c["properties"]["public"]:
  80. classPP = {}
  81. classPP["name"] = pp["name"]
  82. pp["type"] = pp["type"].replace("Polycode::", "")
  83. pp["type"] = pp["type"].replace("std::", "")
  84. classPP["type"] = self.typeFilter(pp["type"])
  85. classPP["cleanType"] = self.cleanTypeFilter(classPP["type"])
  86. if pp["type"].find("POLYIGNORE") != -1:
  87. continue
  88. if pp["name"] == "" or pp["array"] == 1:
  89. continue
  90. if "::union" in pp["name"]:
  91. continue
  92. if "void" in pp["type"]:
  93. continue
  94. if "<" in pp["type"]:
  95. continue
  96. if pp["type"].replace("*", "") in self.ignoreClasses:
  97. continue
  98. if pp["type"].find("static ") != -1:
  99. classPP["isStatic"] = True
  100. if "defaltValue" in pp: #this is misspelled in parser library
  101. classPP["defaultValue"] = pp["defaltValue"]
  102. if 'doxygen' in pp:
  103. classPP["doc"] = self.cleanDocs(pp['doxygen'])
  104. properties.append(classPP)
  105. else:
  106. classPP["isStatic"] = False
  107. 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():
  108. properties.append(classPP)
  109. return properties
  110. # ----------------------------------------------------
  111. # Parse and clean methods
  112. # ----------------------------------------------------
  113. def parseClassMethods(self, c):
  114. methods = []
  115. parsedMethods = []
  116. for pm in c["methods"]["public"]:
  117. method = {}
  118. method["name"] = pm["name"]
  119. if pm["rtnType"].find("static ") == -1:
  120. method["isStatic"] = False
  121. else:
  122. method["isStatic"] = True
  123. method["type"] = self.typeFilter(pm["rtnType"])
  124. method["cleanType"] = self.cleanTypeFilter(method["type"])
  125. if pm["name"] in parsedMethods or pm["name"].find("operator") > -1 or pm["rtnType"].find("POLYIGNORE") > -1 or pm["name"] in self.ignoreMethods :
  126. continue
  127. #ignore destructors
  128. if pm["name"] == "~"+c["name"]:
  129. continue
  130. method["parameters"] = []
  131. for param in pm["parameters"]:
  132. mParam = {}
  133. if not "name" in param:
  134. continue
  135. if not "type" in param:
  136. continue
  137. if param["type"] == "0":
  138. continue
  139. mParam["name"] = param["name"]
  140. mParam["type"] = self.typeFilter(param["type"])
  141. mParam["cleanType"] = self.cleanTypeFilter(mParam["type"])
  142. if "defaltValue" in param:
  143. mParam["defaultValue"] = param["defaltValue"]
  144. method["parameters"].append(mParam)
  145. parsedMethods.append(pm["name"])
  146. methods.append(method)
  147. return methods
  148. # ----------------------------------------------------
  149. # Parse and clean data from a class
  150. # ----------------------------------------------------
  151. def parseClassData(self, c, ckey):
  152. classData = {}
  153. classData["name"] = ckey
  154. if len(c["inherits"]) > 0:
  155. if c["inherits"][0]["class"] not in self.ignoreClasses:
  156. classData["parent"] = c["inherits"][0]["class"]
  157. if 'doxygen' in c:
  158. classData["doc"] = self.cleanDocs(c['doxygen'])
  159. properties = self.parseClassProperties(c)
  160. classData["properties"] = []
  161. classData["staticProperties"] = []
  162. for p in properties:
  163. if p["isStatic"] == True:
  164. classData["staticProperties"].append(p)
  165. else:
  166. classData["properties"].append(p)
  167. classData["methods"] = self.parseClassMethods(c)
  168. return classData
  169. # ----------------------------------------------------
  170. # Parse files and create bindings
  171. # ----------------------------------------------------
  172. def createBindings(self):
  173. print("\nPolycode bindings generator v0.1\n")
  174. print("\033[93mGenerating bindings...")
  175. print("\033[93mParsing files from \033[92m[%s]" % (self.targetDir))
  176. if not os.path.isdir(self.targetDir):
  177. self.error("Target directory not valid!")
  178. return
  179. files = os.listdir(self.targetDir)
  180. filteredFiles = []
  181. for fileName in files:
  182. fileName = "%s/%s" % (self.targetDir, fileName)
  183. if os.path.isdir(fileName):
  184. continue
  185. head, tail = os.path.split(fileName)
  186. ignore = self.ignoreFiles.replace(" ", "").split(",")
  187. if tail.split(".")[1] == "h" and tail.split(".")[0] not in ignore:
  188. filteredFiles.append(fileName)
  189. self.processTargetFile(tail)
  190. for fileName in filteredFiles:
  191. try:
  192. f = open(fileName)
  193. contents = f.read()
  194. for s in self.symbolsToStrip:
  195. contents = contents.replace(s, "")
  196. cppHeader = CppHeaderParser.CppHeader(contents, "string")
  197. for ckey in cppHeader.classes:
  198. if ckey in self.ignoreClasses:
  199. continue
  200. if "::union" in ckey:
  201. continue
  202. print("\033[93mParsing class \033[0m[\033[92m%s\033[0m]" % ckey)
  203. c = cppHeader.classes[ckey]
  204. classData = self.parseClassData(c, ckey)
  205. self.processClass(classData)
  206. except CppHeaderParser.CppParseError as e:
  207. self.error(e)
  208. return
  209. self.finalize()