LuaBindingsGenerator.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 LuaBindingsGenerator(object):
  16. def __init__(self, config):
  17. self.config = config
  18. self.wrappersHeaderList = ""
  19. self.wrappersHeaderBody = ""
  20. self.cppRegisterOut = ""
  21. self.luaClassBindingOut = ""
  22. self.cppLoaderOut = ""
  23. self.luaIndexOut = ""
  24. self.disableGC = self.config.get('lua', 'DisableGarbageCollection').replace(" ", "").split(",")
  25. self.inheritInModule = self.config.get('lua', 'InheritInModule').replace(" ", "").split(",")
  26. self.libName = self.config.get('global', 'LibraryName')
  27. self.cppRegisterOut += "int luaopen_%s(lua_State *L) {\n" % self.libName
  28. if self.libName != "Polycode" and self.libName != "Physics2D" and self.libName != "Physics3D" and self.libName != "UI":
  29. self.cppRegisterOut += "CoreServices *inst = (CoreServices*) *((PolyBase**)lua_touserdata(L, 1));\n"
  30. self.cppRegisterOut += "CoreServices::setInstance(inst);\n"
  31. self.cppRegisterOut += "\tstatic const luaL_Reg %sLib [] = {\n" % (self.libName)
  32. mkdir_p("%s/%s" % (self.config.get('lua', 'LuaApiDirectory'), self.libName))
  33. # ----------------------------------------------------
  34. # Process file
  35. # ----------------------------------------------------
  36. def processTargetFile(self, targetFile):
  37. self.wrappersHeaderList += "#include \"%s/%s\"\n" % (self.config.get('global', 'HeaderIncludeDirectory'), targetFile)
  38. # ----------------------------------------------------
  39. # Process class in file
  40. # ----------------------------------------------------
  41. def processClass(self, c):
  42. inherits = False
  43. parentClass = ""
  44. if "parent" in c:
  45. if c["parent"] in self.inheritInModule: # Parent class is in this module
  46. self.luaClassBindingOut += "require \"%s/%s\"\n\n" % (self.config.get('lua', 'LibraryName'), c["parent"])
  47. else:
  48. self.luaClassBindingOut += "require \"%s/%s\"\n\n" % (self.config.get('lua', 'DefaultModule'), c["parent"])
  49. self.luaClassBindingOut += "class \"%s\" (%s)\n\n" % (c["name"], c["parent"])
  50. parentClass = c["parent"]
  51. inherits = True
  52. if inherits == False:
  53. self.luaClassBindingOut += "class \"%s\"\n\n" % c["name"]
  54. self.generateLuaProperties(c)
  55. self.generateGettersForProperties(c)
  56. self.generateSettersForProperties(c)
  57. self.generateCBindingsForMethods(c)
  58. self.generateLuaMethods(c)
  59. self.cppLoaderOut += "\n\tluaL_newmetatable(L, \"%s.%s\");\n" % (self.libName, c["name"])
  60. if c["name"] not in self.disableGC:
  61. self.cppLoaderOut += "\tlua_pushstring(L, \"__gc\");\n"
  62. self.cppLoaderOut += "\tlua_pushcfunction(L, %s_delete_%s);\n" % (self.libName, c["name"])
  63. self.cppLoaderOut += "\tlua_settable(L, -3);\n"
  64. self.cppLoaderOut +="\tlua_pop(L, 1);\n"
  65. # Delete method (C++ side)
  66. self.cppRegisterOut += "\t\t{\"delete_%s\", %s_delete_%s},\n" % (c["name"], self.libName, c["name"])
  67. self.wrappersHeaderBody += "\tstatic int %s_delete_%s(lua_State *L) {\n" % (self.libName, c["name"])
  68. self.wrappersHeaderBody += "\t\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  69. self.wrappersHeaderBody += "\t\tPolyBase **inst = (PolyBase**)lua_touserdata(L, 1);\n"
  70. self.wrappersHeaderBody += "\t\tdelete ((%s*) *inst);\n" % (c["name"])
  71. self.wrappersHeaderBody += "\t\t*inst = NULL;\n"
  72. self.wrappersHeaderBody += "\t\treturn 0;\n"
  73. self.wrappersHeaderBody += "\t}\n\n"
  74. self.writeClass(c)
  75. self.luaIndexOut += "require \"%s/%s\"\n" % (self.libName, c["name"])
  76. # ----------------------------------------------------
  77. # Write out the C bindings for Lua property setters
  78. # ----------------------------------------------------
  79. def generateSettersForProperties(self, c):
  80. for pp in c["properties"]:
  81. if self.isBasicType(pp["type"]):
  82. self.cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  83. self.wrappersHeaderBody += "static int %s_%s_set_%s(lua_State *L) {\n" % (self.libName, c["name"], pp["name"])
  84. self.wrappersHeaderBody += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  85. self.wrappersHeaderBody += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (c["name"], c["name"])
  86. outfunc = "this_shouldnt_happen"
  87. outfuncsuffix = ""
  88. if pp["type"] == "Number":
  89. outfunc = "lua_tonumber"
  90. if pp["type"] == "String":
  91. outfunc = "lua_tostring"
  92. if pp["type"] == "int":
  93. outfunc = "lua_tointeger"
  94. if pp["type"] == "PolyKEY":
  95. outfunc = "(PolyKEY)lua_tointeger"
  96. if pp["type"] == "bool":
  97. outfunc = "lua_toboolean"
  98. outfuncsuffix = " != 0"
  99. self.wrappersHeaderBody += "\t%s param = %s(L, 2)%s;\n" % (pp["type"], outfunc, outfuncsuffix)
  100. self.wrappersHeaderBody += "\tinst->%s = param;\n" % (pp["name"])
  101. self.wrappersHeaderBody += "\treturn 0;\n"
  102. self.wrappersHeaderBody += "}\n\n"
  103. else:
  104. self.cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  105. self.wrappersHeaderBody += "static int %s_%s_set_%s(lua_State *L) {\n" % (self.libName, c["name"], pp["name"])
  106. self.wrappersHeaderBody += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  107. self.wrappersHeaderBody += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (c["name"], c["name"])
  108. self.wrappersHeaderBody += "\tluaL_checktype(L, 2, LUA_TUSERDATA);\n"
  109. self.wrappersHeaderBody += "\t%s *argInst = (%s*) *((PolyBase**)lua_touserdata(L, 2));\n" % (pp["type"], pp["type"])
  110. self.wrappersHeaderBody += "\tinst->%s = *argInst;\n" % (pp["name"])
  111. self.wrappersHeaderBody += "\treturn 0;\n"
  112. self.wrappersHeaderBody += "}\n\n"
  113. # ----------------------------------------------------
  114. # Write out the C bindings for Lua property getters
  115. # ----------------------------------------------------
  116. def generateGettersForProperties(self, c):
  117. for pp in c["properties"]:
  118. self.cppRegisterOut += "\t\t{\"%s_get_%s\", %s_%s_get_%s},\n" % (c["name"], pp["name"], self.libName, c["name"], pp["name"])
  119. self.wrappersHeaderBody += "static int %s_%s_get_%s(lua_State *L) {\n" % (self.libName, c["name"], pp["name"])
  120. self.wrappersHeaderBody += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  121. self.wrappersHeaderBody += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (c["name"], c["name"])
  122. outfunc = "this_shouldnt_happen"
  123. retFunc = ""
  124. if pp["type"] == "Number":
  125. outfunc = "lua_pushnumber"
  126. if pp["type"] == "String":
  127. outfunc = "lua_pushstring"
  128. retFunc = ".c_str()"
  129. if pp["type"] == "int" or pp["type"] == "PolyKEY":
  130. outfunc = "lua_pushinteger"
  131. if pp["type"] == "bool":
  132. outfunc = "lua_pushboolean"
  133. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool" or pp["type"] == "PolyKEY":
  134. self.wrappersHeaderBody += "\t%s(L, inst->%s%s);\n" % (outfunc, pp["name"], retFunc)
  135. else:
  136. if pp["type"].find("*") != -1:
  137. self.wrappersHeaderBody += "\tif(!inst->%s%s) {\n" % (pp["name"], retFunc)
  138. self.wrappersHeaderBody += "\t\tlua_pushnil(L);\n"
  139. self.wrappersHeaderBody += "\t} else {\n"
  140. self.wrappersHeaderBody += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  141. self.wrappersHeaderBody += "\t\t*userdataPtr = (PolyBase*)inst->%s%s;\n" % (pp["name"], retFunc)
  142. self.wrappersHeaderBody += "\t}\n"
  143. else:
  144. self.wrappersHeaderBody += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  145. self.wrappersHeaderBody += "\t*userdataPtr = (PolyBase*)&inst->%s%s;\n" % (pp["name"], retFunc)
  146. self.wrappersHeaderBody += "\treturn 1;\n"
  147. self.wrappersHeaderBody += "}\n\n"
  148. # ----------------------------------------------------
  149. # Write out the Lua setters and getters for properties in the Lua class
  150. # ----------------------------------------------------
  151. def generateLuaProperties(self, c):
  152. for pp in c["staticProperties"]:
  153. if "defaultValue" in pp:
  154. defaultValue = pp["defaultValue"]
  155. if re.match(r'\s*[a-zA-Z_][a-zA-Z0-9_]*\s*\+', defaultValue):
  156. defaultValue = "%s.%s" % (c["name"], defaultValue)
  157. self.luaClassBindingOut += "%s.%s = %s\n" % (c["name"], pp["name"], defaultValue)
  158. self.luaClassBindingOut += "\n"
  159. pidx = 0
  160. if len(c["properties"]) > 0:
  161. self.luaClassBindingOut += "function %s:__getvar(name)\n" % c["name"]
  162. for pp in c["properties"]:
  163. if pidx == 0:
  164. self.luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  165. else:
  166. self.luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  167. if self.isBasicType(pp["type"]):
  168. self.luaClassBindingOut += "\t\treturn %s.%s_get_%s(self.__ptr)\n" % (self.libName, c["name"], pp["name"])
  169. else:
  170. self.luaClassBindingOut += "\t\tlocal retVal = %s.%s_get_%s(self.__ptr)\n" % (self.libName, c["name"], pp["name"])
  171. self.luaClassBindingOut += self.template_returnPtrLookup("\t\t", self.template_quote(pp["type"]), "retVal")
  172. pidx = pidx + 1
  173. self.luaClassBindingOut += "\tend\n"
  174. if "parent" in c:
  175. self.luaClassBindingOut += "\tif %s[\"__getvar\"] ~= nil then\n" % (c["parent"])
  176. self.luaClassBindingOut += "\t\treturn %s.__getvar(self, name)\n" % (c["parent"])
  177. self.luaClassBindingOut += "\tend\n"
  178. self.luaClassBindingOut += "end\n\n"
  179. self.luaClassBindingOut += "function %s:__setvar(name,value)\n" % c["name"]
  180. pidx = 0
  181. for pp in c["properties"]:
  182. if self.isBasicType(pp["type"]) == True:
  183. if pidx == 0:
  184. self.luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  185. else:
  186. self.luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  187. self.luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value)\n" % (self.libName, c["name"], pp["name"])
  188. self.luaClassBindingOut += "\t\treturn true\n"
  189. else:
  190. if pidx == 0:
  191. self.luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  192. else:
  193. self.luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  194. self.luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value.__ptr)\n" % (self.libName, c["name"], pp["name"])
  195. self.luaClassBindingOut += "\t\treturn true\n"
  196. pidx = pidx + 1
  197. self.luaClassBindingOut += "\tend\n"
  198. if "parent" in c:
  199. self.luaClassBindingOut += "\tif %s[\"__setvar\"] ~= nil then\n" % (c["parent"])
  200. self.luaClassBindingOut += "\t\treturn %s.__setvar(self, name, value)\n" % (c["parent"])
  201. self.luaClassBindingOut += "\telse\n"
  202. self.luaClassBindingOut += "\t\treturn false\n"
  203. self.luaClassBindingOut += "\tend\n"
  204. else:
  205. self.luaClassBindingOut += "\treturn false\n"
  206. self.luaClassBindingOut += "end\n"
  207. # ----------------------------------------------------
  208. # Write out the Lua class file for the class
  209. # ----------------------------------------------------
  210. def writeClass(self, c):
  211. self.luaClassBindingOut += "function %s:__delete()\n" % (c["name"])
  212. self.luaClassBindingOut += "\tif self then %s.delete_%s(self.__ptr) end\n" % (self.libName, c["name"])
  213. self.luaClassBindingOut += "end\n"
  214. if c["name"] != "EventDispatcher":
  215. fout = open("%s/%s/%s.lua" % (self.config.get('lua', 'LuaApiDirectory'), self.libName, c["name"]), "w")
  216. fout.write(self.luaClassBindingOut)
  217. self.luaClassBindingOut = ""
  218. # ----------------------------------------------------
  219. # Create The C binding wrappers for class methods
  220. # ----------------------------------------------------
  221. def generateCBindingsForMethods(self, c):
  222. for method in c["methods"]:
  223. idx = 1
  224. if method["name"] == c["name"]:
  225. self.cppRegisterOut += "\t\t{\"%s\", %s_%s},\n" % (c["name"], self.libName, c["name"])
  226. self.wrappersHeaderBody += "\tstatic int %s_%s(lua_State *L) {\n" % (self.libName, c["name"])
  227. else:
  228. self.cppRegisterOut += "\t\t{\"%s_%s\", %s_%s_%s},\n" % (c["name"], method["name"], self.libName, c["name"], method["name"])
  229. self.wrappersHeaderBody += "\tstatic int %s_%s_%s(lua_State *L) {\n" % (self.libName, c["name"], method["name"])
  230. # if this is not a static method, get the class pointer being passed
  231. if method["isStatic"] == False:
  232. self.wrappersHeaderBody += "\t\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  233. self.wrappersHeaderBody += "\t\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (c["name"], c["name"])
  234. idx = 2
  235. paramlist = []
  236. lparamlist = []
  237. for param in method["parameters"]:
  238. luatype = "LUA_TUSERDATA"
  239. checkfunc = "lua_isuserdata"
  240. if param["type"].find("*") > -1:
  241. luafunc = "(%s) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  242. elif param["type"].find("&") > -1:
  243. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("const", "").replace("&", "").replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  244. else:
  245. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  246. lend = ".__ptr"
  247. luafuncsuffix = ")"
  248. if param["type"] == "int":
  249. luafunc = "lua_tointeger"
  250. luatype = "LUA_TNUMBER"
  251. checkfunc = "lua_isnumber"
  252. luafuncsuffix = ""
  253. lend = ""
  254. if param["type"] == "PolyKEY":
  255. luafunc = "(PolyKEY)lua_tointeger"
  256. luatype = "LUA_TNUMBER"
  257. checkfunc = "lua_isnumber"
  258. luafuncsuffix = ""
  259. lend = ""
  260. if param["type"] == "bool":
  261. luafunc = "lua_toboolean"
  262. luatype = "LUA_TBOOLEAN"
  263. checkfunc = "lua_isboolean"
  264. luafuncsuffix = " != 0"
  265. lend = ""
  266. if param["type"] == "Number":
  267. luatype = "LUA_TNUMBER"
  268. luafunc = "lua_tonumber"
  269. checkfunc = "lua_isnumber"
  270. luafuncsuffix = ""
  271. lend = ""
  272. if param["type"] == "String":
  273. luatype = "LUA_TSTRING"
  274. luafunc = "lua_tostring"
  275. checkfunc = "lua_isstring"
  276. luafuncsuffix = ""
  277. lend = ""
  278. param["type"] = param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle")
  279. if "defaultValue" in param:
  280. if checkfunc != "lua_isuserdata" or (checkfunc == "lua_isuserdata" and param["defaultValue"] == "NULL"):
  281. #param["defaultValue"] = param["defaultValue"].replace(" 0f", ".0f")
  282. param["defaultValue"] = param["defaultValue"].replace(": :", "::")
  283. #param["defaultValue"] = param["defaultValue"].replace("0 ", "0.")
  284. param["defaultValue"] = re.sub(r'([0-9]+) ([0-9])+', r'\1.\2', param["defaultValue"])
  285. self.wrappersHeaderBody += "\t\t%s %s;\n" % (param["type"], param["name"])
  286. self.wrappersHeaderBody += "\t\tif(%s(L, %d)) {\n" % (checkfunc, idx)
  287. self.wrappersHeaderBody += "\t\t\t%s = %s(L, %d)%s;\n" % (param["name"], luafunc, idx, luafuncsuffix)
  288. self.wrappersHeaderBody += "\t\t} else {\n"
  289. self.wrappersHeaderBody += "\t\t\t%s = %s;\n" % (param["name"], param["defaultValue"])
  290. self.wrappersHeaderBody += "\t\t}\n"
  291. else:
  292. self.wrappersHeaderBody += "\t\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  293. if param["type"] == "String":
  294. self.wrappersHeaderBody += "\t\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  295. else:
  296. self.wrappersHeaderBody += "\t\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx,luafuncsuffix)
  297. else:
  298. self.wrappersHeaderBody += "\t\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  299. if param["type"] == "String":
  300. self.wrappersHeaderBody += "\t\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  301. else:
  302. self.wrappersHeaderBody += "\t\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx, luafuncsuffix)
  303. paramlist.append(param["name"])
  304. lparamlist.append(param["name"]+lend)
  305. idx = idx +1 # Param parse success-- mark the increased stack
  306. # Generate C++-side method call / generate return value
  307. if method["name"] == c["name"]: # If constructor
  308. if c["name"] == "EventHandler": # See LuaEventHandler above
  309. self.wrappersHeaderBody += "\t\tLuaEventHandler *inst = new LuaEventHandler();\n"
  310. self.wrappersHeaderBody += "\t\tinst->wrapperIndex = luaL_ref(L, LUA_REGISTRYINDEX );\n"
  311. self.wrappersHeaderBody += "\t\tinst->L = L;\n"
  312. else:
  313. self.wrappersHeaderBody += "\t\t%s *inst = new %s(%s);\n" % (c["name"], c["name"], ", ".join(paramlist))
  314. self.wrappersHeaderBody += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  315. self.wrappersHeaderBody += "\t\t*userdataPtr = (PolyBase*)inst;\n"
  316. self.wrappersHeaderBody += "\t\tluaL_getmetatable(L, \"%s.%s\");\n" % (self.libName, c["name"])
  317. self.wrappersHeaderBody += "\t\tlua_setmetatable(L, -2);\n"
  318. self.wrappersHeaderBody += "\t\treturn 1;\n"
  319. else: #If non-constructor
  320. if method["isStatic"] == False:
  321. call = "inst->%s(%s)" % (method["name"], ", ".join(paramlist))
  322. else:
  323. call = "%s::%s(%s)" % (c["name"], method["name"], ", ".join(paramlist))
  324. if self.isVectorType(method["type"]):
  325. vectorReturnClass = self.getVectorType(method["type"])
  326. if vectorReturnClass.find("&") == -1 and vectorReturnClass.find("*") > -1: #FIXME: return references to std::vectors and basic types
  327. self.wrappersHeaderBody += "\t\tstd::vector<%s> retVector = %s;\n" % (vectorReturnClass,call)
  328. self.wrappersHeaderBody += "\t\tlua_newtable(L);\n"
  329. self.wrappersHeaderBody += "\t\tfor(int i=0; i < retVector.size(); i++) {\n"
  330. self.wrappersHeaderBody += "\t\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  331. self.wrappersHeaderBody += "\t\t\t*userdataPtr = (PolyBase*)retVector[i];\n"
  332. self.wrappersHeaderBody += "\t\t\tlua_rawseti(L, -2, i+1);\n"
  333. self.wrappersHeaderBody += "\t\t}\n"
  334. self.wrappersHeaderBody += "\t\treturn 1;\n"
  335. else:
  336. self.wrappersHeaderBody += "\t\treturn 0;\n"
  337. # else If void-typed:
  338. elif method["type"] == "void" or method["type"] == "static void" or method["type"] == "virtual void" or method["type"] == "inline void":
  339. self.wrappersHeaderBody += "\t\t%s;\n" % (call)
  340. self.wrappersHeaderBody += "\t\treturn 0;\n" # 0 arguments returned
  341. else: # If there is a return value:
  342. # What type is the return value? Default to pointer
  343. outfunc = "this_shouldnt_happen"
  344. retFunc = ""
  345. if method["type"] == "Number" or method["type"] == "inline Number":
  346. outfunc = "lua_pushnumber"
  347. if method["type"] == "String" or method["type"] == "static String": # TODO: Path for STL strings?
  348. outfunc = "lua_pushstring"
  349. retFunc = ".c_str()"
  350. 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":
  351. outfunc = "lua_pushinteger"
  352. if method["type"] == "bool" or method["type"] == "static bool" or method["type"] == "virtual bool":
  353. outfunc = "lua_pushboolean"
  354. if method["type"].find("*") > -1: # Returned var is definitely a pointer.
  355. self.wrappersHeaderBody += "\t\tPolyBase *ptrRetVal = (PolyBase*)%s%s;\n" % (call, retFunc)
  356. self.wrappersHeaderBody += "\t\tif(ptrRetVal == NULL) {\n"
  357. self.wrappersHeaderBody += "\t\t\tlua_pushnil(L);\n"
  358. self.wrappersHeaderBody += "\t\t} else {\n"
  359. self.wrappersHeaderBody += "\t\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  360. self.wrappersHeaderBody += "\t\t\t*userdataPtr = ptrRetVal;\n"
  361. self.wrappersHeaderBody += "\t\t}\n"
  362. elif self.isBasicType(method["type"]) == True:
  363. self.wrappersHeaderBody += "\t\t%s(L, %s%s);\n" % (outfunc, call, retFunc)
  364. else: # Some static object is being returned. Convert it to a pointer, then return that.
  365. className = method["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  366. if className == "Polygon": # Deal with potential windows.h conflict
  367. className = "Polycode::Polygon"
  368. if className == "Rectangle":
  369. className = "Polycode::Rectangle"
  370. if className == "Polycode : : Rectangle":
  371. className = "Polycode::Rectangle"
  372. self.wrappersHeaderBody += "\t\t%s *retInst = new %s();\n" % (className, className)
  373. self.wrappersHeaderBody += "\t\t*retInst = %s;\n" % (call)
  374. self.wrappersHeaderBody += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  375. self.wrappersHeaderBody += "\t\tluaL_getmetatable(L, \"%s.%s\");\n" % (self.libName, className)
  376. self.wrappersHeaderBody += "\t\tlua_setmetatable(L, -2);\n"
  377. self.wrappersHeaderBody += "\t\t*userdataPtr = (PolyBase*)retInst;\n"
  378. self.wrappersHeaderBody += "\t\treturn 1;\n"
  379. self.wrappersHeaderBody += "\t}\n"
  380. # ----------------------------------------------------
  381. # Create Lua API for all class methods
  382. # ----------------------------------------------------
  383. def generateLuaMethods(self, c):
  384. for method in c["methods"]:
  385. paramlist = []
  386. lparamlist = []
  387. for param in method["parameters"]:
  388. paramlist.append(param["name"])
  389. if not self.isBasicType(param["type"]):
  390. lparamlist.append("%s.__ptr" % param["name"])
  391. else:
  392. lparamlist.append(param["name"])
  393. if method["name"] == c["name"]: # Constructor
  394. self.luaClassBindingOut += "function %s:%s(...)\n" % (c["name"], c["name"])
  395. self.luaClassBindingOut += "\tlocal arg = {...}\n"
  396. if "parent" in c:
  397. self.luaClassBindingOut += "\tif type(arg[1]) == \"table\" and count(arg) == 1 then\n"
  398. self.luaClassBindingOut += "\t\tif \"\"..arg[1].__classname == \"%s\" then\n" % (c["parent"])
  399. self.luaClassBindingOut += "\t\t\tself.__ptr = arg[1].__ptr\n"
  400. self.luaClassBindingOut += "\t\t\treturn\n"
  401. self.luaClassBindingOut += "\t\tend\n"
  402. self.luaClassBindingOut += "\tend\n"
  403. self.luaClassBindingOut += "\tfor k,v in pairs(arg) do\n"
  404. self.luaClassBindingOut += "\t\tif type(v) == \"table\" then\n"
  405. self.luaClassBindingOut += "\t\t\tif v.__ptr ~= nil then\n"
  406. self.luaClassBindingOut += "\t\t\t\targ[k] = v.__ptr\n"
  407. self.luaClassBindingOut += "\t\t\tend\n"
  408. self.luaClassBindingOut += "\t\tend\n"
  409. self.luaClassBindingOut += "\tend\n"
  410. self.luaClassBindingOut += "\tif self.__ptr == nil and arg[1] ~= \"__skip_ptr__\" then\n"
  411. if c["name"] == "EventHandler": # See LuaEventHandler above
  412. self.luaClassBindingOut += "\t\tself.__ptr = %s.%s(self)\n" % (self.libName, c["name"])
  413. else:
  414. self.luaClassBindingOut += "\t\tself.__ptr = %s.%s(unpack(arg))\n" % (self.libName, c["name"])
  415. self.luaClassBindingOut += "\tend\n"
  416. self.luaClassBindingOut += "end\n\n"
  417. else: # Non-constructors.
  418. if method["type"].find("static ") == -1: # Non-static method
  419. self.luaClassBindingOut += "function %s:%s(%s)\n" % (c["name"], method["name"], ", ".join(paramlist))
  420. if len(lparamlist):
  421. self.luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr, %s)\n" % (self.libName, c["name"], method["name"], ", ".join(lparamlist))
  422. else:
  423. self.luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr)\n" % (self.libName, c["name"], method["name"])
  424. else: # Static method
  425. self.luaClassBindingOut += "function %s.%s(%s)\n" % (c["name"], method["name"], ", ".join(paramlist))
  426. if len(lparamlist):
  427. self.luaClassBindingOut += "\tlocal retVal = %s.%s_%s(%s)\n" % (self.libName, c["name"], method["name"], ", ".join(lparamlist))
  428. else:
  429. self.luaClassBindingOut += "\tlocal retVal = %s.%s_%s()\n" % (self.libName, c["name"], method["name"])
  430. if method["type"] != "void":
  431. if self.isBasicType(method["type"]):
  432. self.luaClassBindingOut += "\treturn retVal\n"
  433. else:
  434. if self.isVectorType(method["type"]) == True:
  435. className = self.getVectorType(method["type"]).replace("*", "")
  436. self.luaClassBindingOut += self.template_returnPtrLookupArray("\t",self.template_quote(className),"retVal")
  437. else:
  438. className = method["type"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "").replace("*","").replace(" ", "")
  439. self.luaClassBindingOut += self.template_returnPtrLookup("\t",self.template_quote(className),"retVal")
  440. self.luaClassBindingOut += "end\n\n"
  441. # ----------------------------------------------------
  442. # Write out final files
  443. # ----------------------------------------------------
  444. def finalize(self):
  445. with open(self.config.get('lua', 'WrapperHeaderTemplate'), 'r') as f:
  446. out = f.read().replace("%HEADERS%", self.wrappersHeaderList)
  447. out = out.replace("%BODY%", self.wrappersHeaderBody)
  448. fout = open(self.config.get('lua', 'WrapperHeaderTarget'), "w")
  449. fout.write(out)
  450. fout.close()
  451. with open(self.config.get('lua', 'WrapperMainHeaderTemplate'), 'r') as f:
  452. out = f.read().replace("%BODY%", "int _PolyExport luaopen_%s(lua_State *L);" % self.libName)
  453. fout = open(self.config.get('lua', 'WrapperMainHeaderTarget'), "w")
  454. fout.write(out)
  455. fout.close()
  456. self.cppRegisterOut += "\t\t{NULL, NULL}\n"
  457. self.cppRegisterOut += "\t};\n"
  458. self.cppRegisterOut += "\tlua_newtable(L);\n"
  459. self.cppRegisterOut += "\tluaL_setfuncs (L,%sLib,0);\n" % (self.libName)
  460. self.cppRegisterOut += "\tlua_setglobal(L,\"%s\");" % (self.libName)
  461. self.cppRegisterOut += self.cppLoaderOut
  462. self.cppRegisterOut += "\treturn 1;\n"
  463. self.cppRegisterOut += "}"
  464. with open(self.config.get('lua', 'WrapperSourceTemplate'), 'r') as f:
  465. out = f.read().replace("%BODY%", self.cppRegisterOut)
  466. fout = open(self.config.get('lua', 'WrapperSourceTarget'), "w")
  467. fout.write(out)
  468. fout.close()
  469. fout = open("%s/%s.lua" % (self.config.get('lua', 'LuaApiDirectory'), self.libName), "w")
  470. fout.write(self.luaIndexOut)
  471. fout.close()
  472. pattern = '*.lua'
  473. os.chdir(self.config.get('lua', 'LuaApiDirectory'))
  474. with ZipFile("lua_%s.pak" % (self.libName), 'w') as myzip:
  475. for root, dirs, files in os.walk("."):
  476. for filename in fnmatch.filter(files, pattern):
  477. myzip.write(os.path.join(root, filename))
  478. # ----------------------------------------------------
  479. # Utility methods
  480. # ----------------------------------------------------
  481. def isVectorType(self, t):
  482. if t.find("<") > -1 and t.find("vector") > -1:
  483. return True
  484. else:
  485. return False
  486. def getVectorType(self, t):
  487. return t.replace("std::", "").replace("vector<", "").replace(">","").replace(" ", "")
  488. def isBasicType(self, t):
  489. basicTypes = ["int", "Number", "String", "PolyKEY", "bool"]
  490. if t in basicTypes:
  491. return True
  492. else:
  493. return False
  494. def template_returnPtrLookupArray(self, prefix, className, ptr):
  495. out = "%sif %s == nil then return nil end\n" % (prefix, ptr)
  496. out += "%sfor i=1,count(%s) do\n" % (prefix, ptr)
  497. out += "%s\tlocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className.replace("*", ""))
  498. out += "%s\t__c.__ptr = %s[i]\n" % (prefix, ptr)
  499. out += "%s\t%s[i] = __c\n" % (prefix, ptr)
  500. out += "%send\n" % (prefix)
  501. out += "%sreturn %s\n" % (prefix,ptr)
  502. return out
  503. def template_returnPtrLookup(self, prefix, className, ptr):
  504. out = "%sif %s == nil then return nil end\n" % (prefix, ptr)
  505. out += "%slocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className.replace("*", ""))
  506. out += "%s__c.__ptr = %s\n" % (prefix, ptr)
  507. out += "%sreturn __c\n" % (prefix)
  508. return out
  509. def template_quote(self, str):
  510. return "\"%s\"" % str;