JSBindingsGenerator.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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.inheritInModule = self.config.get('global', 'InheritInModule').replace(" ", "").split(",")
  25. self.disableGC = self.config.get('global', 'DisableGarbageCollection').replace(" ", "").split(",")
  26. self.cppRegisterOut += "int jsopen_%s(duk_context *ctx) {\n" % (self.libName)
  27. self.cppRegisterOut += "\tconst duk_function_list_entry %s_funcs[] = {\n" % (self.libName)
  28. mkdir_p("%s/%s" % (self.config.get('js', 'JSApiDirectory'), self.libName))
  29. self.ignoreMethods = self.config.get('global', 'IgnoreMethods').replace(" ", "").split(",")
  30. def processTargetFile(self, targetFile):
  31. self.wrappersHeaderList += "#include \"%s/%s\"\n" % (self.config.get('global', 'HeaderIncludeDirectory'), targetFile)
  32. def processClass(self, c):
  33. inherits = False
  34. parentClass = ""
  35. if "parent" in c:
  36. if c["parent"] in self.inheritInModule: # Parent class is in this module
  37. self.jsClassOut += "require('%s/%s')\n\n" % (self.config.get('global', 'LibraryName'), c["parent"])
  38. else:
  39. self.jsClassOut += "require('%s/%s')\n\n" % (self.config.get('global', 'DefaultModule'), c["parent"])
  40. parentClass = c["parent"]
  41. inherits = True
  42. constructor = None
  43. for method in c["methods"]:
  44. if method["name"] == c["name"]:
  45. constructor = method
  46. params = ""
  47. paramList = []
  48. if constructor:
  49. params = ",".join(str(p["name"]) for p in constructor["parameters"])
  50. paramList = constructor["parameters"]
  51. self.jsClassOut += "function %s(%s) {\n" % (c["name"], params)
  52. if c["name"] not in self.ignoreMethods:
  53. self.jsClassOut += "\tif(arguments[0] != \"__skip_ptr__\") {\n"
  54. self.jsClassOut += "\t\tthis.__ptr = %s.%s(%s)\n" % (self.libName, c["name"], params)
  55. self.jsClassOut += "\t}\n"
  56. self.cppRegisterOut += "\t\t\t{\"%s\", %s_%s, %d},\n" % (c["name"], self.libName, c["name"], len(paramList))
  57. self.wrappersHeaderBody += "\tduk_ret_t %s_%s(duk_context *context) {\n" % (self.libName, c["name"])
  58. idx = 0
  59. for p in paramList:
  60. if "*" in p["type"]:
  61. outfunc = "(%s)duk_to_pointer" % (p["type"])
  62. outtype = "%s" % p["type"]
  63. else:
  64. outfunc = "*(%s*)duk_to_pointer" % (p["type"])
  65. outtype = "%s" % p["type"]
  66. if p["type"] == "int":
  67. outfunc = "duk_to_int"
  68. outtype = "int"
  69. if p["type"] == "PolyKEY":
  70. outfunc = "(PolyKEY)duk_to_int"
  71. outtype = "PolyKEY"
  72. if p["type"] == "Number":
  73. outfunc = "duk_to_number"
  74. outtype = "Number"
  75. if p["type"] == "bool":
  76. outfunc = "duk_to_boolean"
  77. outtype = "bool"
  78. if p["type"] == "String":
  79. outfunc = "duk_to_string"
  80. outtype = "String"
  81. self.wrappersHeaderBody += "\t\t%s %s = %s(context, %d);\n" % (outtype, p["name"], outfunc, idx)
  82. idx += 1
  83. self.wrappersHeaderBody += "\t\t%s *inst = new %s(%s);\n" % (c["name"], c["name"], params)
  84. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)inst);\n"
  85. self.wrappersHeaderBody += "\t\treturn 1;\n"
  86. self.wrappersHeaderBody += "\t}\n\n"
  87. self.makeJSProperties(c)
  88. self.jsClassOut += "}\n\n"
  89. if inherits:
  90. self.jsClassOut += "%s.prototype = Object.create(%s.prototype);\n\n" % (c["name"], parentClass)
  91. self.makeJSPropAccessors(c)
  92. if c["name"] not in self.disableGC:
  93. self.jsClassOut += "Duktape.fin(%s.prototype, function (x) {\n" % (c["name"])
  94. self.jsClassOut += "\tif (x === %s.prototype) {\n" % (c["name"])
  95. self.jsClassOut += "\t\treturn;\n"
  96. self.jsClassOut += "\t}\n"
  97. self.jsClassOut += "\t%s.%s__delete(x.__ptr)\n" % (self.libName, c["name"])
  98. self.jsClassOut += "})\n"
  99. self.cppRegisterOut += "\t\t\t{\"%s__delete\", %s_%s__delete, 1},\n" % (c["name"], self.libName, c["name"])
  100. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__delete(duk_context *context) {\n" % (self.libName, c["name"])
  101. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  102. self.wrappersHeaderBody += "\t\tdelete inst;\n"
  103. self.wrappersHeaderBody += "\t\treturn 0;\n"
  104. self.wrappersHeaderBody += "\t}\n\n"
  105. self.makeJSMethods(c)
  106. self.writeClass(c)
  107. self.jsIndexOut += "require('%s/%s')\n" % (self.libName, c["name"])
  108. def makeJSPropAccessors(self, c):
  109. if len(c["properties"]) > 0:
  110. for pp in c["properties"]:
  111. self.jsClassOut += "%s.prototype.__get_%s = function() {\n" % (c["name"], pp["name"])
  112. self.cppRegisterOut += "\t\t\t{\"%s__get_%s\", %s_%s__get_%s, 1},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  113. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__get_%s(duk_context *context) {\n" % (self.libName, c["name"], pp["name"])
  114. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  115. outfunc = "this_shouldnt_happen"
  116. retFunc = ""
  117. if pp["type"] == "Number":
  118. outfunc = "duk_push_number"
  119. if pp["type"] == "String":
  120. outfunc = "duk_push_string"
  121. retFunc = ".c_str()"
  122. if pp["type"] == "int" or pp["type"] == "PolyKEY":
  123. outfunc = "duk_push_int"
  124. if pp["type"] == "bool":
  125. outfunc = "duk_push_boolean"
  126. if pp["type"].find("*") > -1: # Returned var is definitely a pointer.
  127. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)inst->%s%s;\n" % (pp["name"], retFunc)
  128. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)ptrRetVal);\n"
  129. self.jsClassOut += "\tvar retVal = new %s()\n\tretVal.__ptr = " % (pp["cleanType"])
  130. self.jsClassOut += "\t%s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  131. self.jsClassOut += "\treturn retVal\n"
  132. self.jsClassOut += "}\n\n"
  133. elif self.isBasicType(pp["type"]) == True:
  134. self.wrappersHeaderBody += "\t\t%s(context, inst->%s%s);\n" % (outfunc, pp["name"], retFunc);
  135. self.jsClassOut += "\treturn %s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  136. self.jsClassOut += "}\n\n"
  137. else:
  138. className = pp["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  139. if className == "Polygon": # Deal with potential windows.h conflict
  140. className = "Polycode::Polygon"
  141. if className == "Rectangle":
  142. className = "Polycode::Rectangle"
  143. if className == "Polycode : : Rectangle":
  144. className = "Polycode::Rectangle"
  145. self.wrappersHeaderBody += "\t\t%s *retInst = new %s();\n" % (className, className)
  146. self.wrappersHeaderBody += "\t\t*retInst = inst->%s%s;\n" % (pp["name"], retFunc)
  147. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)retInst);\n"
  148. self.jsClassOut += "\tvar retVal = new %s()\n\tretVal.__ptr = " % (pp["cleanType"])
  149. self.jsClassOut += "\t%s.%s__get_%s(this.__ptr)\n" % (self.libName, c["name"], pp["name"])
  150. self.jsClassOut += "\treturn retVal\n"
  151. self.jsClassOut += "}\n\n"
  152. self.wrappersHeaderBody += "\t\treturn 1;\n"
  153. self.wrappersHeaderBody += "\t}\n\n"
  154. self.jsClassOut += "%s.prototype.__set_%s = function(val) {\n" % (c["name"], pp["name"])
  155. if self.isBasicType(pp["type"]):
  156. self.jsClassOut += "\t%s.%s__set_%s(this.__ptr, val)\n" % (self.libName, c["name"], pp["name"])
  157. else:
  158. self.jsClassOut += "\t%s.%s__set_%s(this.__ptr, val.__ptr)\n" % (self.libName, c["name"], pp["name"])
  159. self.jsClassOut += "}\n\n"
  160. self.cppRegisterOut += "\t\t\t{\"%s__set_%s\", %s_%s__set_%s, 2},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  161. self.wrappersHeaderBody += "\tduk_ret_t %s_%s__set_%s(duk_context *context) {\n" % (self.libName, c["name"], pp["name"])
  162. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  163. outfunc = "this_shouldnt_happen"
  164. if "*" in pp["type"]:
  165. outfunc = "(%s)duk_to_pointer" % (pp["type"])
  166. else:
  167. outfunc = "*(%s*)duk_to_pointer" % (pp["type"])
  168. if pp["type"] == "int":
  169. outfunc = "duk_to_int"
  170. if pp["type"] == "PolyKEY":
  171. outfunc = "(PolyKEY)duk_to_int"
  172. if pp["type"] == "Number":
  173. outfunc = "duk_to_number"
  174. if pp["type"] == "bool":
  175. outfunc = "duk_to_boolean"
  176. if pp["type"] == "String":
  177. outfunc = "duk_to_string"
  178. self.wrappersHeaderBody += "\t\tinst->%s = %s(context, 1);\n" % (pp["name"], outfunc)
  179. self.wrappersHeaderBody += "\t\treturn 0;\n"
  180. self.wrappersHeaderBody += "\t}\n\n"
  181. def makeJSProperties(self, c):
  182. if len(c["properties"]) > 0:
  183. self.jsClassOut += "\tObject.defineProperties(this, {\n"
  184. idx = 0
  185. for pp in c["properties"]:
  186. 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"])
  187. if idx < len(c["properties"])-1:
  188. self.jsClassOut += ","
  189. self.jsClassOut += "\n"
  190. idx += 1
  191. self.jsClassOut += "\t})\n"
  192. def makeJSMethods(self, c):
  193. for method in c["methods"]:
  194. if method["name"] != c["name"]:
  195. self.jsClassOut += "\n%s.prototype.%s = function(" % (c["name"], method["name"])
  196. params = ",".join(str(p["name"]) for p in method["parameters"])
  197. self.jsClassOut += params
  198. self.jsClassOut += ") {\n"
  199. 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)
  200. self.wrappersHeaderBody += "\tduk_ret_t %s_%s_%s(duk_context *context) {\n" % (self.libName, c["name"], method["name"])
  201. if not method["isStatic"]:
  202. self.wrappersHeaderBody += "\t\t%s *inst = (%s*)duk_to_pointer(context, 0);\n" % (c["name"], c["name"])
  203. idx = 1
  204. if method["isStatic"]:
  205. idx = 0
  206. for p in method["parameters"]:
  207. if "*" in p["type"]:
  208. outfunc = "(%s)duk_to_pointer" % (p["type"])
  209. outtype = "%s" % p["type"]
  210. else:
  211. outfunc = "*(%s*)duk_to_pointer" % (p["type"])
  212. outtype = "%s" % p["type"]
  213. if p["type"] == "int":
  214. outfunc = "duk_to_int"
  215. outtype = "int"
  216. if p["type"] == "PolyKEY":
  217. outfunc = "(PolyKEY)duk_to_int"
  218. outtype = "PolyKEY"
  219. if p["type"] == "Number":
  220. outfunc = "duk_to_number"
  221. outtype = "Number"
  222. if p["type"] == "bool":
  223. outfunc = "duk_to_boolean"
  224. outtype = "bool"
  225. if p["type"] == "String":
  226. outfunc = "duk_to_string"
  227. outtype = "String"
  228. self.wrappersHeaderBody += "\t\t%s %s = %s(context, %d);\n" % (outtype, p["name"], outfunc, idx)
  229. idx += 1
  230. jsRet = ""
  231. finalOut = ""
  232. if self.isVectorType(method["type"]):
  233. self.wrappersHeaderBody += "\t\treturn 0;\n"
  234. elif method["type"] == "void" or method["type"] == "static void" or method["type"] == "virtual void" or method["type"] == "inline void" or method["type"] == "void*":
  235. if method["isStatic"]:
  236. self.wrappersHeaderBody += "\t\t%s::%s(%s);\n" % (c["name"], method["name"], params)
  237. else:
  238. self.wrappersHeaderBody += "\t\tinst->%s(%s);\n" % (method["name"], params)
  239. self.wrappersHeaderBody += "\t\treturn 0;\n"
  240. else:
  241. outfunc = "this_shouldnt_happen"
  242. retFunc = ""
  243. if method["type"] == "Number" or method["type"] == "inline Number":
  244. outfunc = "duk_push_number"
  245. if method["type"] == "String" or method["type"] == "static String": # TODO: Path for STL strings?
  246. outfunc = "duk_push_string"
  247. retFunc = ".c_str()"
  248. 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":
  249. outfunc = "duk_push_int"
  250. if method["type"] == "bool" or method["type"] == "static bool" or method["type"] == "virtual bool":
  251. outfunc = "duk_push_boolean"
  252. if method["type"].find("*") > -1: # Returned var is definitely a pointer.
  253. if method["isStatic"]:
  254. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)%s::%s(%s)%s;\n" % (c["name"], method["name"], params, retFunc)
  255. else:
  256. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)inst->%s(%s)%s;\n" % (method["name"], params, retFunc)
  257. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)ptrRetVal);\n"
  258. jsRet = "var retVal = new %s()\n\tretVal.__ptr = " % (method["cleanType"])
  259. finalOut = "\treturn retVal\n"
  260. elif self.isBasicType(method["type"]) == True:
  261. if method["isStatic"]:
  262. self.wrappersHeaderBody += "\t\t%s(context, %s::%s(%s)%s);\n" % (outfunc, c["name"], method["name"], params, retFunc);
  263. else:
  264. self.wrappersHeaderBody += "\t\t%s(context, inst->%s(%s)%s);\n" % (outfunc, method["name"], params, retFunc);
  265. jsRet = "return "
  266. else:
  267. className = method["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  268. if className == "Polygon": # Deal with potential windows.h conflict
  269. className = "Polycode::Polygon"
  270. if className == "Rectangle":
  271. className = "Polycode::Rectangle"
  272. if className == "Polycode : : Rectangle":
  273. className = "Polycode::Rectangle"
  274. self.wrappersHeaderBody += "\t\t%s *retInst = new %s();\n" % (className, className)
  275. if method["isStatic"]:
  276. self.wrappersHeaderBody += "\t\t*retInst = %s::%s(%s)%s;\n" % (c["name"], method["name"], params, retFunc)
  277. else:
  278. self.wrappersHeaderBody += "\t\t*retInst = inst->%s(%s)%s;\n" % (method["name"], params, retFunc)
  279. self.wrappersHeaderBody += "\t\tduk_push_pointer(context, (void*)retInst);\n"
  280. jsRet = "var retVal = new %s()\n\tretVal.__ptr = " % (method["cleanType"])
  281. finalOut = "\treturn retVal\n"
  282. self.wrappersHeaderBody += "\t\treturn 1;\n"
  283. self.wrappersHeaderBody += "\t}\n\n"
  284. if len(params) > 0:
  285. jsParams = ""
  286. jidx = 0
  287. for jp in method["parameters"]:
  288. if jp["type"].find("*") > -1:
  289. jsParams += "%s.__ptr" % jp["name"]
  290. else:
  291. jsParams += jp["name"]
  292. jidx += 1
  293. if jidx < len(method["parameters"]):
  294. jsParams += ", "
  295. if method["isStatic"]:
  296. self.jsClassOut += "\t%s%s.%s_%s(%s)\n" % (jsRet, self.libName, c["name"], method["name"], jsParams)
  297. else:
  298. self.jsClassOut += "\t%s%s.%s_%s(this.__ptr, %s)\n" % (jsRet, self.libName, c["name"], method["name"], jsParams)
  299. else:
  300. if method["isStatic"]:
  301. self.jsClassOut += "\t%s%s.%s_%s()\n" % (jsRet, self.libName, c["name"], method["name"])
  302. else:
  303. self.jsClassOut += "\t%s%s.%s_%s(this.__ptr)\n" % (jsRet, self.libName, c["name"], method["name"])
  304. self.jsClassOut += finalOut
  305. self.jsClassOut += "}\n"
  306. def isBasicType(self, t):
  307. basicTypes = ["int", "Number", "String", "PolyKEY", "bool"]
  308. if t in basicTypes:
  309. return True
  310. else:
  311. return False
  312. def isVectorType(self, t):
  313. if t.find("<") > -1 and t.find("vector") > -1:
  314. return True
  315. else:
  316. return False
  317. def finalize(self):
  318. fout = open("%s/%s.js" % (self.config.get('js', 'JSApiDirectory'), self.libName), "w")
  319. fout.write(self.jsIndexOut)
  320. self.jsClassOut = ""
  321. with open(self.config.get('js', 'WrapperHeaderTemplate'), 'r') as f:
  322. out = f.read().replace("%HEADERS%", self.wrappersHeaderList)
  323. out = out.replace("%BODY%", self.wrappersHeaderBody)
  324. fout = open(self.config.get('js', 'WrapperHeaderTarget'), "w")
  325. fout.write(out)
  326. fout.close()
  327. with open(self.config.get('js', 'WrapperMainHeaderTemplate'), 'r') as f:
  328. out = f.read().replace("%BODY%", "int _PolyExport jsopen_%s(duk_context *ctx);" % self.libName)
  329. fout = open(self.config.get('js', 'WrapperMainHeaderTarget'), "w")
  330. fout.write(out)
  331. fout.close()
  332. self.cppRegisterOut += "\t\t\t{NULL, NULL, 0}\n"
  333. self.cppRegisterOut += "\t};\n"
  334. self.cppRegisterOut += "\tduk_push_global_object(ctx);\n"
  335. self.cppRegisterOut += "\tduk_push_object(ctx);\n"
  336. self.cppRegisterOut += "\tduk_put_function_list(ctx, -1, %s_funcs);\n" % (self.libName)
  337. self.cppRegisterOut += "\tduk_put_prop_string(ctx, -2, \"%s\");\n" % (self.libName)
  338. self.cppRegisterOut += "\tduk_pop(ctx);\n"
  339. self.cppRegisterOut += "\treturn 1;\n"
  340. self.cppRegisterOut += "}\n"
  341. with open(self.config.get('js', 'WrapperSourceTemplate'), 'r') as f:
  342. out = f.read().replace("%BODY%", self.cppRegisterOut)
  343. fout = open(self.config.get('js', 'WrapperSourceTarget'), "w")
  344. fout.write(out)
  345. fout.close()
  346. curDir = os.path.dirname(os.path.realpath(__file__))
  347. pattern = '*.js'
  348. os.chdir(self.config.get('js', 'JSApiDirectory'))
  349. with ZipFile("js_%s.pak" % (self.libName), 'w') as myzip:
  350. for root, dirs, files in os.walk("."):
  351. for filename in fnmatch.filter(files, pattern):
  352. myzip.write(os.path.join(root, filename))
  353. os.chdir(curDir)
  354. def writeClass(self, c):
  355. fout = open("%s/%s/%s.js" % (self.config.get('js', 'JSApiDirectory'), self.libName, c["name"]), "w")
  356. fout.write(self.jsClassOut)
  357. self.jsClassOut = ""