JSBindingsGenerator.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import ConfigParser
  2. import io
  3. import os
  4. import re
  5. from zipfile import *
  6. import fnmatch
  7. import errno
  8. def mkdir_p(path):
  9. try:
  10. os.makedirs(path)
  11. except OSError as e:
  12. if e.errno == errno.EEXIST:
  13. pass
  14. else: raise
  15. class JSBindingsGenerator(object):
  16. def __init__(self, config):
  17. self.config = config
  18. self.libName = self.config.get('global', 'LibraryName')
  19. self.jsClassOut = ""
  20. self.jsIndexOut = ""
  21. self.wrappersHeaderList = ""
  22. self.wrappersHeaderBody = ""
  23. self.cppRegisterOut = ""
  24. self.disableGC = self.config.get('global', 'DisableGarbageCollection').replace(" ", "").split(",")
  25. self.cppRegisterOut += "int jsopen_%s(duk_context *ctx) {\n" % (self.libName)
  26. self.cppRegisterOut += "\tconst duk_function_list_entry %s_funcs[] = {\n" % (self.libName)
  27. mkdir_p("%s/%s" % (self.config.get('js', 'JSApiDirectory'), self.libName))
  28. def processTargetFile(self, targetFile):
  29. self.wrappersHeaderList += "#include \"%s/%s\"\n" % (self.config.get('global', 'HeaderIncludeDirectory'), targetFile)
  30. def processClass(self, c):
  31. self.jsClassOut += "function %s() {\n" % c["name"]
  32. self.makeJSProperties(c)
  33. self.jsClassOut += "}\n"
  34. self.makeJSPropAccessors(c)
  35. if c["name"] not in self.disableGC:
  36. self.jsClassOut += "Duktape.fin(%s.prototype, function (x) {\n" % (c["name"])
  37. self.jsClassOut += "\tif (x === %s.prototype) {\n" % (c["name"])
  38. self.jsClassOut += "\t\treturn;\n"
  39. self.jsClassOut += "\t}\n"
  40. self.jsClassOut += "\t%s.%s__delete(x.__ptr)\n" % (self.libName, c["name"])
  41. self.jsClassOut += "})\n"
  42. self.cppRegisterOut += "\t\t\t{\"%s__delete\", %s_%s__delete, 1},\n" % (c["name"], self.libName, c["name"])
  43. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__delete(duk_context *context) {\n" % (self.libName, c["name"])
  44. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  45. self.wrappersHeaderBody += "\t\tdelete inst;\n"
  46. self.wrappersHeaderBody += "\t\treturn 0;\n"
  47. self.wrappersHeaderBody += "\t}\n\n"
  48. self.makeJSMethods(c)
  49. self.writeClass(c)
  50. self.jsIndexOut += "require('%s/%s')\n" % (self.libName, c["name"])
  51. def makeJSPropAccessors(self, c):
  52. if len(c["properties"]) > 0:
  53. for pp in c["properties"]:
  54. self.jsClassOut += "%s.prototype.__get_%s = function() {\n" % (c["name"], pp["name"])
  55. self.cppRegisterOut += "\t\t\t{\"%s__get_%s\", %s_%s__get_%s, 1},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  56. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__get_%s(duk_context *context) {\n" % (self.libName, c["name"], pp["name"])
  57. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  58. outfunc = "this_shouldnt_happen"
  59. retFunc = ""
  60. if pp["type"] == "Number":
  61. outfunc = "duk_push_number"
  62. if pp["type"] == "String":
  63. outfunc = "duk_push_string"
  64. retFunc = ".c_str()"
  65. if pp["type"] == "int" or pp["type"] == "PolyKEY":
  66. outfunc = "duk_push_int"
  67. if pp["type"] == "bool":
  68. outfunc = "duk_push_boolean"
  69. if pp["type"].find("*") > -1: # Returned var is definitely a pointer.
  70. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)inst->%s%s;\n" % (pp["name"], retFunc)
  71. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)ptrRetVal);\n"
  72. self.jsClassOut += "\tvar retVal = new %s()\n\tretVal.__ptr = " % (pp["type"].replace("*", ""))
  73. self.jsClassOut += "\t%s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  74. self.jsClassOut += "\treturn retVal\n"
  75. self.jsClassOut += "}\n\n"
  76. elif self.isBasicType(pp["type"]) == True:
  77. self.wrappersHeaderBody += "\t\t%s(context, inst->%s%s);\n" % (outfunc, pp["name"], retFunc);
  78. self.jsClassOut += "\treturn %s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  79. self.jsClassOut += "}\n\n"
  80. else:
  81. className = pp["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  82. if className == "Polygon": # Deal with potential windows.h conflict
  83. className = "Polycode::Polygon"
  84. if className == "Rectangle":
  85. className = "Polycode::Rectangle"
  86. if className == "Polycode : : Rectangle":
  87. className = "Polycode::Rectangle"
  88. self.wrappersHeaderBody += "\t\t%s *retInst = new %s();\n" % (className, className)
  89. self.wrappersHeaderBody += "\t\t*retInst = inst->%s%s;\n" % (pp["name"], retFunc)
  90. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)retInst);\n"
  91. self.jsClassOut += "\tvar retVal = new %s()\n\tretVal.__ptr = " % (pp["type"].replace("*", ""))
  92. self.jsClassOut += "\t%s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  93. self.jsClassOut += "\treturn retVal\n"
  94. self.jsClassOut += "}\n\n"
  95. self.wrappersHeaderBody += "\t\treturn 1;\n"
  96. self.wrappersHeaderBody += "\t}\n\n"
  97. self.jsClassOut += "%s.prototype.__set_%s = function(val) {\n" % (c["name"], pp["name"])
  98. if self.isBasicType(pp["type"]):
  99. self.jsClassOut += "\t%s.%s__set_%s(this.__ptr, val)\n" % (self.libName, c["name"], pp["name"])
  100. else:
  101. self.jsClassOut += "\t%s.%s__set_%s(this.__ptr, val.__ptr)\n" % (self.libName, c["name"], pp["name"])
  102. self.jsClassOut += "}\n\n"
  103. self.cppRegisterOut += "\t\t\t{\"%s__set_%s\", %s_%s__set_%s, 2},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  104. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__set_%s(duk_context *context) {\n" % (self.libName, c["name"], pp["name"])
  105. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  106. outfunc = "this_shouldnt_happen"
  107. if "*" in pp["type"]:
  108. outfunc = "(%s)duk_to_pointer" % (pp["type"])
  109. else:
  110. outfunc = "*(%s*)duk_to_pointer" % (pp["type"])
  111. if pp["type"] == "int":
  112. outfunc = "duk_to_int"
  113. if pp["type"] == "PolyKEY":
  114. outfunc = "(PolyKEY)duk_to_int"
  115. if pp["type"] == "Number":
  116. outfunc = "duk_to_number"
  117. if pp["type"] == "bool":
  118. outfunc = "duk_to_boolean"
  119. if pp["type"] == "String":
  120. outfunc = "duk_to_string"
  121. self.wrappersHeaderBody += "\t\tinst->%s = %s(context, 1);\n" % (pp["name"], outfunc)
  122. self.wrappersHeaderBody += "\t\treturn 0;\n"
  123. self.wrappersHeaderBody += "\t}\n\n"
  124. def makeJSProperties(self, c):
  125. if len(c["properties"]) > 0:
  126. self.jsClassOut += "\tObject.defineProperties(this, {\n"
  127. idx = 0
  128. for pp in c["properties"]:
  129. self.jsClassOut += "\t\t'%s': { enumerable: true, configurable: true, get: %s.prototype.__get_%s, set: %s.prototype.__set_%s}" % (pp["name"], c["name"], pp["name"], c["name"], pp["name"])
  130. if idx < len(c["properties"])-1:
  131. self.jsClassOut += ","
  132. self.jsClassOut += "\n"
  133. idx += 1
  134. self.jsClassOut += "\t})\n"
  135. def makeJSMethods(self, c):
  136. for method in c["methods"]:
  137. if method["isStatic"] == False and method["name"] != c["name"]:
  138. self.jsClassOut += "\n%s.prototype.%s = function(" % (c["name"], method["name"])
  139. params = ",".join(str(p["name"]) for p in method["parameters"])
  140. self.jsClassOut += params
  141. self.jsClassOut += ") {\n"
  142. self.cppRegisterOut += "\t\t\t{\"%s_%s\", %s_%s_%s, %d},\n" % (c["name"], method["name"], self.libName, c["name"], method["name"], len(method["parameters"]) + 1)
  143. self.wrappersHeaderBody += "\tduk_ret_t %s_%s_%s(duk_context *context) {\n" % (self.libName, c["name"], method["name"])
  144. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  145. idx = 1
  146. for p in method["parameters"]:
  147. if "*" in p["type"]:
  148. outfunc = "(%s)duk_to_pointer" % (p["type"])
  149. outtype = "%s" % p["type"]
  150. else:
  151. outfunc = "*(%s*)duk_to_pointer" % (p["type"])
  152. outtype = "%s" % p["type"]
  153. if p["type"] == "int":
  154. outfunc = "duk_to_int"
  155. outtype = "int"
  156. if p["type"] == "PolyKEY":
  157. outfunc = "(PolyKEY)duk_to_int"
  158. outtype = "PolyKEY"
  159. if p["type"] == "Number":
  160. outfunc = "duk_to_number"
  161. outtype = "Number"
  162. if p["type"] == "bool":
  163. outfunc = "duk_to_boolean"
  164. outtype = "bool"
  165. if p["type"] == "String":
  166. outfunc = "duk_to_string"
  167. outtype = "String"
  168. self.wrappersHeaderBody += "\t\t%s %s = %s(context, %d);\n" % (outtype, p["name"], outfunc, idx)
  169. idx += 1
  170. jsRet = ""
  171. finalOut = ""
  172. if self.isVectorType(method["type"]):
  173. self.wrappersHeaderBody += "\t\treturn 0;\n"
  174. elif method["type"] == "void" or method["type"] == "static void" or method["type"] == "virtual void" or method["type"] == "inline void" or method["type"] == "void*":
  175. self.wrappersHeaderBody += "\t\tinst->%s(%s);\n" % (method["name"], params)
  176. self.wrappersHeaderBody += "\t\treturn 0;\n"
  177. else:
  178. outfunc = "this_shouldnt_happen"
  179. retFunc = ""
  180. if method["type"] == "Number" or method["type"] == "inline Number":
  181. outfunc = "duk_push_number"
  182. if method["type"] == "String" or method["type"] == "static String": # TODO: Path for STL strings?
  183. outfunc = "duk_push_string"
  184. retFunc = ".c_str()"
  185. if method["type"] == "int" or method["type"] == "unsigned int" or method["type"] == "static int" or method["type"] == "size_t" or method["type"] == "static size_t" or method["type"] == "long" or method["type"] == "unsigned int" or method["type"] == "static long" or method["type"] == "short" or method["type"] == "PolyKEY" or method["type"] == "wchar_t":
  186. outfunc = "duk_push_int"
  187. if method["type"] == "bool" or method["type"] == "static bool" or method["type"] == "virtual bool":
  188. outfunc = "duk_push_boolean"
  189. if method["type"].find("*") > -1: # Returned var is definitely a pointer.
  190. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)inst->%s(%s)%s;\n" % (method["name"], params, retFunc)
  191. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)ptrRetVal);\n"
  192. jsRet = "var retVal = new %s()\n\tretVal.__ptr = " % (method["type"].replace("*", ""))
  193. finalOut = "\treturn retVal\n"
  194. elif self.isBasicType(method["type"]) == True:
  195. self.wrappersHeaderBody += "\t\t%s(context, inst->%s(%s)%s);\n" % (outfunc, method["name"], params, retFunc);
  196. jsRet = "return "
  197. else:
  198. className = method["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  199. if className == "Polygon": # Deal with potential windows.h conflict
  200. className = "Polycode::Polygon"
  201. if className == "Rectangle":
  202. className = "Polycode::Rectangle"
  203. if className == "Polycode : : Rectangle":
  204. className = "Polycode::Rectangle"
  205. self.wrappersHeaderBody += "\t\t%s *retInst = new %s();\n" % (className, className)
  206. self.wrappersHeaderBody += "\t\t*retInst = inst->%s(%s)%s;\n" % (method["name"], params, retFunc)
  207. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)retInst);\n"
  208. jsRet = "var retVal = new %s()\n\tretVal.__ptr = " % (method["type"].replace("*", ""))
  209. finalOut = "\treturn retVal\n"
  210. self.wrappersHeaderBody += "\t\treturn 1;\n"
  211. self.wrappersHeaderBody += "\t}\n\n"
  212. if len(params) > 0:
  213. self.jsClassOut += "\t%s%s.%s_%s(this.__ptr, %s)\n" % (jsRet, self.libName, c["name"], method["name"], params)
  214. else:
  215. self.jsClassOut += "\t%s%s.%s_%s(this.__ptr)\n" % (jsRet, self.libName, c["name"], method["name"])
  216. self.jsClassOut += finalOut
  217. self.jsClassOut += "}\n"
  218. def isBasicType(self, t):
  219. basicTypes = ["int", "Number", "String", "PolyKEY", "bool"]
  220. if t in basicTypes:
  221. return True
  222. else:
  223. return False
  224. def isVectorType(self, t):
  225. if t.find("<") > -1 and t.find("vector") > -1:
  226. return True
  227. else:
  228. return False
  229. def finalize(self):
  230. fout = open("%s/%s.js" % (self.config.get('js', 'JSApiDirectory'), self.libName), "w")
  231. fout.write(self.jsIndexOut)
  232. self.jsClassOut = ""
  233. with open(self.config.get('js', 'WrapperHeaderTemplate'), 'r') as f:
  234. out = f.read().replace("%HEADERS%", self.wrappersHeaderList)
  235. out = out.replace("%BODY%", self.wrappersHeaderBody)
  236. fout = open(self.config.get('js', 'WrapperHeaderTarget'), "w")
  237. fout.write(out)
  238. fout.close()
  239. with open(self.config.get('js', 'WrapperMainHeaderTemplate'), 'r') as f:
  240. out = f.read().replace("%BODY%", "int _PolyExport jsopen_%s(duk_context *ctx);" % self.libName)
  241. fout = open(self.config.get('js', 'WrapperMainHeaderTarget'), "w")
  242. fout.write(out)
  243. fout.close()
  244. self.cppRegisterOut += "\t\t\t{NULL, NULL, 0}\n"
  245. self.cppRegisterOut += "\t};\n"
  246. self.cppRegisterOut += "\tduk_push_global_object(ctx);\n"
  247. self.cppRegisterOut += "\tduk_push_object(ctx);\n"
  248. self.cppRegisterOut += "\tduk_put_function_list(ctx, -1, %s_funcs);\n" % (self.libName)
  249. self.cppRegisterOut += "\tduk_put_prop_string(ctx, -2, \"%s\");\n" % (self.libName)
  250. self.cppRegisterOut += "\tduk_pop(ctx);\n"
  251. self.cppRegisterOut += "\treturn 1;\n"
  252. self.cppRegisterOut += "}\n"
  253. with open(self.config.get('js', 'WrapperSourceTemplate'), 'r') as f:
  254. out = f.read().replace("%BODY%", self.cppRegisterOut)
  255. fout = open(self.config.get('js', 'WrapperSourceTarget'), "w")
  256. fout.write(out)
  257. fout.close()
  258. curDir = os.path.dirname(os.path.realpath(__file__))
  259. pattern = '*.js'
  260. os.chdir(self.config.get('js', 'JSApiDirectory'))
  261. with ZipFile("js_%s.pak" % (self.libName), 'w') as myzip:
  262. for root, dirs, files in os.walk("."):
  263. for filename in fnmatch.filter(files, pattern):
  264. myzip.write(os.path.join(root, filename))
  265. os.chdir(curDir)
  266. def writeClass(self, c):
  267. fout = open("%s/%s/%s.js" % (self.config.get('js', 'JSApiDirectory'), self.libName, c["name"]), "w")
  268. fout.write(self.jsClassOut)
  269. self.jsClassOut = ""