BindingsGenerator.py 7.3 KB

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