create_lua_library.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. import sys
  2. import CppHeaderParser
  3. import os
  4. import errno
  5. import re
  6. from zipfile import *
  7. import fnmatch
  8. import re
  9. def mkdir_p(path): # Same effect as mkdir -p, create dir and all necessary parent dirs
  10. try:
  11. os.makedirs(path)
  12. except OSError as e:
  13. if e.errno == errno.EEXIST: # Dir already exists; not really an error
  14. pass
  15. else: raise
  16. # Note we expect className to be a valid string
  17. def template_returnPtrLookup(prefix, className, ptr):
  18. out = ""
  19. out += "%sif _G[\"__ptr_lookup\"][%s][%s] ~= nil then\n" % (prefix, className, ptr)
  20. out += "%s\treturn _G[\"__ptr_lookup\"][%s][%s]\n" % (prefix, className, ptr)
  21. out += "%selse\n" % (prefix)
  22. out += "%s\t_G[\"__ptr_lookup\"][%s][%s] = _G[%s](\"__skip_ptr__\")\n" % (prefix, className, ptr, className)
  23. out += "%s\t_G[\"__ptr_lookup\"][%s][%s].__ptr = %s\n" % (prefix, className, ptr, ptr)
  24. out += "%s\treturn _G[\"__ptr_lookup\"][%s][%s]\n" % (prefix, className, ptr)
  25. out += "%send\n" % (prefix)
  26. return out
  27. def template_quote(str):
  28. return "\"%s\"" % str;
  29. # FIXME: Some "unsigned int *" functions are still being generated on the polycode API?
  30. def typeFilter(ty):
  31. ty = ty.replace("Polycode::", "")
  32. ty = ty.replace("std::", "")
  33. ty = ty.replace("const", "")
  34. ty = ty.replace("&", "")
  35. ty = re.sub(r'^.*\sint\s*$', 'int', ty) # eg "unsigned int"
  36. ty = re.sub(r'^.*\slong\s*$', 'int', ty)
  37. ty = re.sub(r'^.*\sfloat\s*$', 'Number', ty)
  38. ty = re.sub(r'^.*\sdouble\s*$', 'Number', ty) # eg "long double"
  39. ty = ty.replace("unsigned", "int")
  40. ty = ty.replace("long", "int")
  41. ty = ty.replace("float", "Number")
  42. ty = ty.replace("double", "Number")
  43. ty = ty.replace(" ", "") # Not very safe!
  44. return ty
  45. def createLUABindings(inputPath, prefix, mainInclude, libSmallName, libName, apiPath, apiClassPath, includePath, sourcePath, inheritInModuleFiles):
  46. wrappersHeaderOut = "" # Def: Global C++ *LUAWrappers.h
  47. cppRegisterOut = "" # Def: Global C++ *LUA.cpp
  48. luaIndexOut = "" # Def: Global Lua everything-gets-required-from-this-file file
  49. # Header boilerplate for wrappersHeaderOut and cppRegisterOut
  50. cppRegisterOut += "#include \"%sLUA.h\"\n" % (prefix)
  51. cppRegisterOut += "#include \"%sLUAWrappers.h\"\n" % (prefix)
  52. cppRegisterOut += "#include \"PolyCoreServices.h\"\n\n"
  53. cppRegisterOut += "using namespace Polycode;\n\n"
  54. cppRegisterOut += "int luaopen_%s(lua_State *L) {\n" % (prefix)
  55. if prefix != "Polycode":
  56. cppRegisterOut += "CoreServices *inst = (CoreServices*)lua_topointer(L, 1);\n"
  57. cppRegisterOut += "CoreServices::setInstance(inst);\n"
  58. cppRegisterOut += "\tstatic const struct luaL_reg %sLib [] = {" % (libSmallName)
  59. wrappersHeaderOut += "#pragma once\n\n"
  60. wrappersHeaderOut += "extern \"C\" {\n\n"
  61. wrappersHeaderOut += "#include <stdio.h>\n"
  62. wrappersHeaderOut += "#include \"lua.h\"\n"
  63. wrappersHeaderOut += "#include \"lualib.h\"\n"
  64. wrappersHeaderOut += "#include \"lauxlib.h\"\n"
  65. wrappersHeaderOut += "} // extern \"C\" \n\n"
  66. # Get list of headers to create bindings from
  67. inputPathIsDir = os.path.isdir(inputPath)
  68. if inputPathIsDir:
  69. files = os.listdir(inputPath)
  70. else:
  71. files = []
  72. with open(inputPath) as f:
  73. for line in f.readlines():
  74. files.append(line.strip()) # Strip whitespace, path/
  75. filteredFiles = []
  76. for fileName in files:
  77. if inputPathIsDir:
  78. fileName = "%s/%s" % (inputPath, fileName)
  79. head, tail = os.path.split(fileName)
  80. ignore = ["PolyGLSLProgram", "PolyGLSLShader", "PolyGLSLShaderModule", "PolyWinCore", "PolyCocoaCore", "PolyAGLCore", "PolySDLCore", "Poly_iPhone", "PolyGLES1Renderer", "PolyGLRenderer", "tinyxml", "tinystr", "OpenGLCubemap", "PolyiPhoneCore", "PolyGLES1Texture", "PolyGLTexture", "PolyGLVertexBuffer", "PolyThreaded", "PolyGLHeaders", "GLee", "PolyPeer", "PolySocket", "PolyClient", "PolyServer", "PolyServerWorld"]
  81. if tail.split(".")[1] == "h" and tail.split(".")[0] not in ignore:
  82. filteredFiles.append(fileName)
  83. wrappersHeaderOut += "#include \"%s\"\n" % (tail)
  84. wrappersHeaderOut += "\nusing namespace std;\n\n"
  85. wrappersHeaderOut += "\nnamespace Polycode {\n\n"
  86. # Special case: If we are building the Polycode library itself, inject the LuaEventHandler class.
  87. # Note: so that event callbacks can work, any object inheriting from EventHandler will secretly
  88. # be modified to actually inherit from LuaEventHandler instead.
  89. if prefix == "Polycode":
  90. wrappersHeaderOut += "class LuaEventHandler : public EventHandler {\n"
  91. wrappersHeaderOut += "public:\n"
  92. wrappersHeaderOut += " LuaEventHandler() : EventHandler() {}\n"
  93. wrappersHeaderOut += " void handleEvent(Event *e) {\n"
  94. wrappersHeaderOut += " lua_getfield(L, LUA_GLOBALSINDEX, \"EventHandler\" );\n"
  95. wrappersHeaderOut += " lua_getfield(L, -1, \"__handleEvent\");\n"
  96. wrappersHeaderOut += " lua_rawgeti( L, LUA_REGISTRYINDEX, wrapperIndex );\n"
  97. wrappersHeaderOut += " lua_pushlightuserdata(L, e);\n"
  98. # wrappersHeaderOut += " lua_getfield (L, LUA_GLOBALSINDEX, \"__customError\");\n"
  99. # wrappersHeaderOut += " int errH = lua_gettop(L);\n"
  100. # wrappersHeaderOut += " lua_pcall(L, 2, 0, errH);\n"
  101. wrappersHeaderOut += " lua_pcall(L, 2, 0, 0);\n"
  102. wrappersHeaderOut += " }\n"
  103. wrappersHeaderOut += " int wrapperIndex;\n"
  104. wrappersHeaderOut += " lua_State *L;\n"
  105. wrappersHeaderOut += "};\n\n"
  106. # Iterate, process each input file
  107. for fileName in filteredFiles:
  108. # "Package owned" classes that ship with Polycode
  109. inheritInModule = ["PhysicsSceneEntity", "CollisionScene", "CollisionSceneEntity"]
  110. # A file or comma-separated list of files can be given to specify classes which are "package owned"
  111. # and should not be inherited out of Polycode/. The files should contain one class name per line,
  112. # and the class name may be prefixed with a path (which will be ignored).
  113. if inheritInModuleFiles:
  114. for moduleFileName in inheritInModuleFiles.split(","):
  115. with open(moduleFileName) as f:
  116. for line in f.readlines():
  117. inheritInModule.append(line.strip().split("/",1)[-1]) # Strip whitespace, path/
  118. print "Parsing %s" % fileName
  119. try: # One input file parse.
  120. f = open(fileName) # Def: Input file handle
  121. contents = f.read().replace("_PolyExport", "") # Def: Input file contents, strip out "_PolyExport"
  122. cppHeader = CppHeaderParser.CppHeader(contents, "string") # Def: Input file contents, parsed structure
  123. ignore_classes = ["PolycodeShaderModule", "Object", "Threaded", "OpenGLCubemap"]
  124. # Iterate, check each class in this file.
  125. for ckey in cppHeader.classes:
  126. print ">> Parsing class %s" % ckey
  127. c = cppHeader.classes[ckey] # Def: The class structure
  128. luaClassBindingOut = "" # Def: The local lua file to generate for this class.
  129. inherits = False
  130. parentClass = ""
  131. if len(c["inherits"]) > 0: # Does this class have parents?
  132. if c["inherits"][0]["class"] not in ignore_classes:
  133. if c["inherits"][0]["class"] in inheritInModule: # Parent class is in this module
  134. luaClassBindingOut += "require \"%s/%s\"\n\n" % (prefix, c["inherits"][0]["class"])
  135. else: # Parent class is in Polycore
  136. luaClassBindingOut += "require \"Polycode/%s\"\n\n" % (c["inherits"][0]["class"])
  137. if (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter"):
  138. luaClassBindingOut += "require \"Polycode/ParticleEmitter\"\n\n"
  139. luaClassBindingOut += "class \"%s\" (%s)\n\n" % (ckey, c["inherits"][0]["class"])
  140. parentClass = c["inherits"][0]["class"]
  141. inherits = True
  142. if inherits == False: # Class does not have parents
  143. luaClassBindingOut += "class \"%s\"\n\n" % ckey
  144. if ckey in ignore_classes:
  145. continue
  146. if len(c["methods"]["public"]) < 2: # Used to, this was a continue.
  147. print("Warning: Lua-binding class with less than two methods")
  148. continue # FIXME: Remove this, move any non-compileable classes into ignore_classes
  149. parsed_methods = [] # Def: List of discovered methods
  150. ignore_methods = ["readByte32", "readByte16", "getCustomEntitiesByType", "Core", "Renderer", "Shader", "Texture", "handleEvent", "secondaryHandler", "getSTLString"]
  151. luaClassBindingOut += "\n\n"
  152. classProperties = [] # Def: List of found property structures ("properties" meaning "data members")
  153. for pp in c["properties"]["public"]:
  154. pp["type"] = pp["type"].replace("Polycode::", "")
  155. pp["type"] = pp["type"].replace("std::", "")
  156. if pp["type"].find("POLYIGNORE") != -1:
  157. continue
  158. if pp["type"].find("static ") != -1: # If static. FIXME: Static doesn't work?
  159. if "defaltValue" in pp: # FIXME: defaltValue is misspelled.
  160. luaClassBindingOut += "%s.%s = %s\n" % (ckey, pp["name"], pp["defaltValue"])
  161. else: # FIXME: Nonstatic method ? variable ?? found.
  162. #there are some bugs in the class parser that cause it to return junk
  163. if pp["type"].find("*") == -1 and pp["type"].find("vector") == -1 and pp["name"] != "setScale" and pp["name"] != "setPosition" and pp["name"] != "BUFFER_CACHE_PRECISION" and not pp["name"].isdigit():
  164. classProperties.append(pp)
  165. # Iterate over properties, creating getters
  166. pidx = 0 # Def: Count of properties processed so far
  167. # TODO: Remove or generalize ParticleEmitter special casing. These lines are marked with #SPEC
  168. if len(classProperties) > 0: # If there are properties, add index lookup to the metatable
  169. luaClassBindingOut += "function %s:__getvar(name)\n" % ckey
  170. # Iterate over property structures, creating if/else clauses for each.
  171. # TODO: Could a table be more appropriate for
  172. for pp in classProperties:
  173. pp["type"] = typeFilter(pp["type"])
  174. if pidx == 0:
  175. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  176. else:
  177. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  178. # Generate Lua side of binding:
  179. # If type is a primitive such as Number/String/int/bool
  180. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool":
  181. luaClassBindingOut += "\t\treturn %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  182. # If type is a particle emitter, specifically #SPEC
  183. elif (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter":
  184. luaClassBindingOut += "\t\tlocal ret = %s(\"__skip_ptr__\")\n" % (pp["type"])
  185. luaClassBindingOut += "\t\tret.__ptr = self.__ptr\n"
  186. luaClassBindingOut += "\t\treturn ret\n"
  187. # If type is a class
  188. else:
  189. luaClassBindingOut += "\t\tlocal retVal = %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  190. luaClassBindingOut += template_returnPtrLookup("\t\t", template_quote(pp["type"]), "retVal")
  191. # Generate C++ side of binding:
  192. if not ((ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter"): #SPEC
  193. cppRegisterOut += "\t\t{\"%s_get_%s\", %s_%s_get_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  194. wrappersHeaderOut += "static int %s_%s_get_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  195. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TLIGHTUSERDATA);\n"
  196. wrappersHeaderOut += "\t%s *inst = (%s*)lua_topointer(L, 1);\n" % (ckey, ckey)
  197. outfunc = "lua_pushlightuserdata"
  198. retFunc = ""
  199. if pp["type"] == "Number":
  200. outfunc = "lua_pushnumber"
  201. if pp["type"] == "String":
  202. outfunc = "lua_pushstring"
  203. retFunc = ".c_str()"
  204. if pp["type"] == "int":
  205. outfunc = "lua_pushinteger"
  206. if pp["type"] == "bool":
  207. outfunc = "lua_pushboolean"
  208. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool":
  209. wrappersHeaderOut += "\t%s(L, inst->%s%s);\n" % (outfunc, pp["name"], retFunc)
  210. else:
  211. wrappersHeaderOut += "\t%s(L, &inst->%s%s);\n" % (outfunc, pp["name"], retFunc)
  212. wrappersHeaderOut += "\treturn 1;\n"
  213. wrappersHeaderOut += "}\n\n"
  214. # Success
  215. pidx = pidx + 1
  216. luaClassBindingOut += "\tend\n"
  217. if inherits:
  218. luaClassBindingOut += "\tif %s[\"__getvar\"] ~= nil then\n" % (parentClass)
  219. luaClassBindingOut += "\t\treturn %s.__getvar(self, name)\n" % (parentClass)
  220. luaClassBindingOut += "\tend\n"
  221. luaClassBindingOut += "end\n"
  222. luaClassBindingOut += "\n\n"
  223. # Iterate over properties again, creating setters
  224. pidx = 0 # Def: Count of
  225. if len(classProperties) > 0: # If there are properties, add index setter to the metatable
  226. luaClassBindingOut += "function %s:__setvar(name,value)\n" % ckey
  227. for pp in classProperties:
  228. pp["type"] = typeFilter(pp["type"])
  229. # If type is a primitive: Create lua and C++ sides at the same time.
  230. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool":
  231. if pidx == 0:
  232. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  233. else:
  234. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  235. luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value)\n" % (libName, ckey, pp["name"])
  236. luaClassBindingOut += "\t\treturn true\n"
  237. cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  238. wrappersHeaderOut += "static int %s_%s_set_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  239. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TLIGHTUSERDATA);\n"
  240. wrappersHeaderOut += "\t%s *inst = (%s*)lua_topointer(L, 1);\n" % (ckey, ckey)
  241. outfunc = "lua_topointer"
  242. if pp["type"] == "Number":
  243. outfunc = "lua_tonumber"
  244. if pp["type"] == "String":
  245. outfunc = "lua_tostring"
  246. if pp["type"] == "int":
  247. outfunc = "lua_tointeger"
  248. if pp["type"] == "bool":
  249. outfunc = "lua_toboolean"
  250. wrappersHeaderOut += "\t%s param = %s(L, 2);\n" % (pp["type"], outfunc)
  251. wrappersHeaderOut += "\tinst->%s = param;\n" % (pp["name"])
  252. wrappersHeaderOut += "\treturn 0;\n"
  253. wrappersHeaderOut += "}\n\n"
  254. pidx = pidx + 1 # Success
  255. # Notice: Setters for object types are not created.
  256. if pidx != 0:
  257. luaClassBindingOut += "\tend\n"
  258. if inherits:
  259. luaClassBindingOut += "\tif %s[\"__setvar\"] ~= nil then\n" % (parentClass)
  260. luaClassBindingOut += "\t\treturn %s.__setvar(self, name, value)\n" % (parentClass)
  261. luaClassBindingOut += "\telse\n"
  262. luaClassBindingOut += "\t\treturn false\n"
  263. luaClassBindingOut += "\tend\n"
  264. else:
  265. luaClassBindingOut += "\treturn false\n"
  266. luaClassBindingOut += "end\n"
  267. # Iterate over methods
  268. luaClassBindingOut += "\n\n"
  269. for pm in c["methods"]["public"]:
  270. # Skip argument-overloaded methods and operators.
  271. # TODO: Instead of skipping arguemnt overloads, have special behavior.
  272. # TODO: Instead of skipping operators, add to metatable.
  273. if pm["name"] in parsed_methods or pm["name"].find("operator") > -1 or pm["rtnType"].find("POLYIGNORE") > -1 or pm["name"] in ignore_methods:
  274. continue
  275. # Skip destructors and methods which return templates.
  276. # TODO: Special-case certain kind of vector<>s?
  277. if pm["name"] == "~"+ckey or pm["rtnType"].find("<") > -1:
  278. continue
  279. basicType = False
  280. voidRet = False
  281. # Def: True if method takes a lua_State* as argument (i.e.: no preprocessing by us)
  282. rawMethod = len(pm["parameters"]) > 0 and pm["parameters"][0].get("type","").find("lua_State") > -1
  283. # Basic setup, C++ side: Add function to registry and start building wrapper function.
  284. if pm["name"] == ckey: # It's a constructor
  285. cppRegisterOut += "\t\t{\"%s\", %s_%s},\n" % (ckey, libName, ckey)
  286. wrappersHeaderOut += "static int %s_%s(lua_State *L) {\n" % (libName, ckey)
  287. idx = 1 # Def: Current stack depth (TODO: Figure out, is this correct?)
  288. else: # It's not a constructor
  289. cppRegisterOut += "\t\t{\"%s_%s\", %s_%s_%s},\n" % (ckey, pm["name"], libName, ckey, pm["name"])
  290. wrappersHeaderOut += "static int %s_%s_%s(lua_State *L) {\n" % (libName, ckey, pm["name"])
  291. # Skip static methods (TODO: Figure out, why is this being done here?). # FIXME
  292. if pm["rtnType"].find("static ") == -1:
  293. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TLIGHTUSERDATA);\n"
  294. wrappersHeaderOut += "\t%s *inst = (%s*)lua_topointer(L, 1);\n" % (ckey, ckey)
  295. idx = 2
  296. else:
  297. idx = 1
  298. if rawMethod:
  299. wrappersHeaderOut += "\treturn inst->%s(L);\n" % (pm["name"])
  300. else:
  301. # Generate C++ side parameter pushing
  302. paramlist = []
  303. lparamlist = []
  304. for param in pm["parameters"]:
  305. if not param.has_key("type"):
  306. continue
  307. if param["type"] == "0":
  308. continue
  309. param["type"] = typeFilter(param["type"])
  310. param["name"] = param["name"].replace("end", "_end").replace("repeat", "_repeat")
  311. if"type" in param:
  312. luatype = "LUA_TLIGHTUSERDATA"
  313. checkfunc = "lua_islightuserdata"
  314. if param["type"].find("*") > -1:
  315. luafunc = "(%s)lua_topointer" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  316. elif param["type"].find("&") > -1:
  317. luafunc = "*(%s*)lua_topointer" % (param["type"].replace("const", "").replace("&", "").replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  318. else:
  319. luafunc = "*(%s*)lua_topointer" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  320. lend = ".__ptr"
  321. if param["type"] == "int" or param["type"] == "unsigned int":
  322. luafunc = "lua_tointeger"
  323. luatype = "LUA_TNUMBER"
  324. checkfunc = "lua_isnumber"
  325. lend = ""
  326. if param["type"] == "bool":
  327. luafunc = "lua_toboolean"
  328. luatype = "LUA_TBOOLEAN"
  329. checkfunc = "lua_isboolean"
  330. lend = ""
  331. if param["type"] == "Number" or param["type"] == "float" or param["type"] == "double":
  332. luatype = "LUA_TNUMBER"
  333. luafunc = "lua_tonumber"
  334. checkfunc = "lua_isnumber"
  335. lend = ""
  336. if param["type"] == "String":
  337. luatype = "LUA_TSTRING"
  338. luafunc = "lua_tostring"
  339. checkfunc = "lua_isstring"
  340. lend = ""
  341. param["type"] = param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle")
  342. if "defaltValue" in param:
  343. if checkfunc != "lua_islightuserdata" or (checkfunc == "lua_islightuserdata" and param["defaltValue"] == "NULL"):
  344. #param["defaltValue"] = param["defaltValue"].replace(" 0f", ".0f")
  345. param["defaltValue"] = param["defaltValue"].replace(": :", "::")
  346. #param["defaltValue"] = param["defaltValue"].replace("0 ", "0.")
  347. param["defaltValue"] = re.sub(r'([0-9]+) ([0-9])+', r'\1.\2', param["defaltValue"])
  348. wrappersHeaderOut += "\t%s %s;\n" % (param["type"], param["name"])
  349. wrappersHeaderOut += "\tif(%s(L, %d)) {\n" % (checkfunc, idx)
  350. wrappersHeaderOut += "\t\t%s = %s(L, %d);\n" % (param["name"], luafunc, idx)
  351. wrappersHeaderOut += "\t} else {\n"
  352. wrappersHeaderOut += "\t\t%s = %s;\n" % (param["name"], param["defaltValue"])
  353. wrappersHeaderOut += "\t}\n"
  354. else:
  355. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  356. if param["type"] == "String":
  357. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  358. else:
  359. wrappersHeaderOut += "\t%s %s = %s(L, %d);\n" % (param["type"], param["name"], luafunc, idx)
  360. else:
  361. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  362. if param["type"] == "String":
  363. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  364. else:
  365. wrappersHeaderOut += "\t%s %s = %s(L, %d);\n" % (param["type"], param["name"], luafunc, idx)
  366. paramlist.append(param["name"])
  367. lparamlist.append(param["name"]+lend)
  368. idx = idx +1 # Param parse success-- mark the increased stack
  369. # Generate C++-side method call / generate return value
  370. if pm["name"] == ckey: # If constructor
  371. if ckey == "EventHandler": # See LuaEventHandler above
  372. wrappersHeaderOut += "\tLuaEventHandler *inst = new LuaEventHandler();\n"
  373. wrappersHeaderOut += "\tinst->wrapperIndex = luaL_ref(L, LUA_REGISTRYINDEX );\n"
  374. wrappersHeaderOut += "\tinst->L = L;\n"
  375. else:
  376. wrappersHeaderOut += "\t%s *inst = new %s(%s);\n" % (ckey, ckey, ", ".join(paramlist))
  377. wrappersHeaderOut += "\tlua_pushlightuserdata(L, (void*)inst);\n"
  378. wrappersHeaderOut += "\treturn 1;\n"
  379. else: #If non-constructor
  380. if pm["rtnType"].find("static ") == -1: # If non-static
  381. call = "inst->%s(%s)" % (pm["name"], ", ".join(paramlist))
  382. else: # If static (FIXME: Why doesn't this work?)
  383. call = "%s::%s(%s)" % (ckey, pm["name"], ", ".join(paramlist))
  384. # If void-typed:
  385. if pm["rtnType"] == "void" or pm["rtnType"] == "static void" or pm["rtnType"] == "virtual void" or pm["rtnType"] == "inline void":
  386. wrappersHeaderOut += "\t%s;\n" % (call)
  387. basicType = True
  388. voidRet = True
  389. wrappersHeaderOut += "\treturn 0;\n" # 0 arguments returned
  390. else: # If there is a return value:
  391. # What type is the return value? Default to pointer
  392. outfunc = "lua_pushlightuserdata"
  393. retFunc = ""
  394. basicType = False
  395. if pm["rtnType"] == "Number" or pm["rtnType"] == "inline Number":
  396. outfunc = "lua_pushnumber"
  397. basicType = True
  398. if pm["rtnType"] == "String" or pm["rtnType"] == "static String": # TODO: Path for STL strings?
  399. outfunc = "lua_pushstring"
  400. basicType = True
  401. retFunc = ".c_str()"
  402. if pm["rtnType"] == "int" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static int" or pm["rtnType"] == "size_t" or pm["rtnType"] == "static size_t" or pm["rtnType"] == "long" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static long":
  403. outfunc = "lua_pushinteger"
  404. basicType = True
  405. if pm["rtnType"] == "bool" or pm["rtnType"] == "static bool" or pm["rtnType"] == "virtual bool":
  406. outfunc = "lua_pushboolean"
  407. basicType = True
  408. if pm["rtnType"].find("*") > -1: # Returned var is definitely a pointer.
  409. wrappersHeaderOut += "\tvoid *ptrRetVal = (void*)%s%s;\n" % (call, retFunc)
  410. wrappersHeaderOut += "\tif(ptrRetVal == NULL) {\n"
  411. wrappersHeaderOut += "\t\tlua_pushnil(L);\n"
  412. wrappersHeaderOut += "\t} else {\n"
  413. wrappersHeaderOut += "\t\t%s(L, ptrRetVal);\n" % (outfunc)
  414. wrappersHeaderOut += "\t}\n"
  415. elif basicType == True: # Returned var has been flagged as a recognized primitive type
  416. wrappersHeaderOut += "\t%s(L, %s%s);\n" % (outfunc, call, retFunc)
  417. else: # Some static object is being returned. Convert it to a pointer, then return that.
  418. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  419. if className == "Polygon": # Deal with potential windows.h conflict
  420. className = "Polycode::Polygon"
  421. if className == "Rectangle":
  422. className = "Polycode::Rectangle"
  423. if className == "Polycode : : Rectangle":
  424. className = "Polycode::Rectangle"
  425. wrappersHeaderOut += "\t%s *retInst = new %s();\n" % (className, className)
  426. wrappersHeaderOut += "\t*retInst = %s;\n" % (call)
  427. wrappersHeaderOut += "\t%s(L, retInst);\n" % (outfunc)
  428. wrappersHeaderOut += "\treturn 1;\n"
  429. wrappersHeaderOut += "}\n\n" # Close out C++ generation
  430. # Now generate the Lua side method.
  431. if rawMethod:
  432. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, pm["name"])
  433. luaClassBindingOut += "\treturn %s.%s_%s(self.__ptr, ...)\n" % (libName, ckey, pm["name"])
  434. luaClassBindingOut += "end\n"
  435. elif pm["name"] == ckey: # Constructors
  436. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, ckey)
  437. luaClassBindingOut += "\tlocal arg = {...}\n"
  438. if inherits:
  439. luaClassBindingOut += "\tif type(arg[1]) == \"table\" and count(arg) == 1 then\n"
  440. luaClassBindingOut += "\t\tif \"\"..arg[1].__classname == \"%s\" then\n" % (c["inherits"][0]["class"])
  441. luaClassBindingOut += "\t\t\tself.__ptr = arg[1].__ptr\n"
  442. luaClassBindingOut += "\t\t\treturn\n"
  443. luaClassBindingOut += "\t\tend\n"
  444. luaClassBindingOut += "\tend\n"
  445. luaClassBindingOut += "\tfor k,v in pairs(arg) do\n"
  446. luaClassBindingOut += "\t\tif type(v) == \"table\" then\n"
  447. luaClassBindingOut += "\t\t\tif v.__ptr ~= nil then\n"
  448. luaClassBindingOut += "\t\t\t\targ[k] = v.__ptr\n"
  449. luaClassBindingOut += "\t\t\tend\n"
  450. luaClassBindingOut += "\t\tend\n"
  451. luaClassBindingOut += "\tend\n"
  452. luaClassBindingOut += "\tif self.__ptr == nil and arg[1] ~= \"__skip_ptr__\" then\n"
  453. if ckey == "EventHandler": # See LuaEventHandler above
  454. luaClassBindingOut += "\t\tself.__ptr = %s.%s(self)\n" % (libName, ckey)
  455. else:
  456. luaClassBindingOut += "\t\tself.__ptr = %s.%s(unpack(arg))\n" % (libName, ckey)
  457. luaClassBindingOut += "\t\t_G[\"__ptr_lookup\"].%s[self.__ptr] = self\n" % (ckey)
  458. luaClassBindingOut += "\tend\n"
  459. luaClassBindingOut += "end\n\n"
  460. else: # Non-constructors.
  461. if pm["rtnType"].find("static ") == -1: # Non-static method
  462. luaClassBindingOut += "function %s:%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  463. if len(lparamlist):
  464. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr, %s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  465. else:
  466. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr)\n" % (libName, ckey, pm["name"])
  467. else: # Static method
  468. luaClassBindingOut += "function %s.%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  469. if len(lparamlist):
  470. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(%s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  471. else:
  472. luaClassBindingOut += "\tlocal retVal = %s.%s_%s()\n" % (libName, ckey, pm["name"])
  473. if not voidRet: # Was there a return value?
  474. if basicType == True: # Yes, a primitive
  475. luaClassBindingOut += "\treturn retVal\n"
  476. else: # Yes, a pointer was returned
  477. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "").replace("*","").replace(" ", "")
  478. luaClassBindingOut += "\tif retVal == nil then return nil end\n"
  479. luaClassBindingOut += template_returnPtrLookup("\t",template_quote(className),"retVal")
  480. luaClassBindingOut += "end\n\n" # Close out Lua generation
  481. parsed_methods.append(pm["name"]) # Method parse success
  482. # With methods out of the way, do some final cleanup:
  483. # Delete method (C++ side)
  484. cppRegisterOut += "\t\t{\"delete_%s\", %s_delete_%s},\n" % (ckey, libName, ckey)
  485. wrappersHeaderOut += "static int %s_delete_%s(lua_State *L) {\n" % (libName, ckey)
  486. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TLIGHTUSERDATA);\n"
  487. wrappersHeaderOut += "\t%s *inst = (%s*)lua_topointer(L, 1);\n" % (ckey, ckey)
  488. wrappersHeaderOut += "\tdelete inst;\n"
  489. wrappersHeaderOut += "\treturn 0;\n"
  490. wrappersHeaderOut += "}\n\n"
  491. luaClassBindingOut += "\n\n"
  492. luaClassBindingOut += "if not _G[\"__ptr_lookup\"] then _G[\"__ptr_lookup\"] = {} end\n"
  493. luaClassBindingOut += "_G[\"__ptr_lookup\"].%s = {}\n\n" % (ckey)
  494. # Delete method (Lua side)
  495. luaClassBindingOut += "function %s:__delete()\n" % (ckey)
  496. luaClassBindingOut += "\t_G[\"__ptr_lookup\"].%s[self.__ptr] = nil\n" % (ckey)
  497. luaClassBindingOut += "\t%s.delete_%s(self.__ptr)\n" % (libName, ckey)
  498. luaClassBindingOut += "end\n"
  499. if ckey == "EventHandler": # See LuaEventHandler above
  500. luaClassBindingOut += "\n\n"
  501. luaClassBindingOut += "function EventHandler:__handleEvent(event)\n"
  502. luaClassBindingOut += "\tevt = _G[\"Event\"](\"__skip_ptr__\")\n"
  503. luaClassBindingOut += "\tevt.__ptr = event\n"
  504. luaClassBindingOut += "\tself:handleEvent(evt)\n"
  505. #luaClassBindingOut += "\tself:handleEvent(event)\n"
  506. luaClassBindingOut += "end\n\n"
  507. # Let's use this opportunity to put in some other "generated" utility functions.
  508. luaClassBindingOut += "function __ptrToTable(className, ptr)\n"
  509. luaClassBindingOut += template_returnPtrLookup("\t","className","ptr")
  510. luaClassBindingOut += "end\n\n"
  511. # Add class to lua index file
  512. luaIndexOut += "require \"%s/%s\"\n" % (prefix, ckey)
  513. # Write lua file
  514. mkdir_p(apiClassPath)
  515. fout = open("%s/%s.lua" % (apiClassPath, ckey), "w")
  516. fout.write(luaClassBindingOut)
  517. except CppHeaderParser.CppParseError, e: # One input file parse; failed.
  518. print e
  519. sys.exit(1)
  520. # Footer boilerplate for wrappersHeaderOut and cppRegisterOut.
  521. wrappersHeaderOut += "} // namespace Polycode\n"
  522. cppRegisterOut += "\t\t{NULL, NULL}\n"
  523. cppRegisterOut += "\t};\n"
  524. cppRegisterOut += "\tluaL_openlib(L, \"%s\", %sLib, 0);\n" % (libName, libSmallName)
  525. cppRegisterOut += "\treturn 1;\n"
  526. cppRegisterOut += "}"
  527. cppRegisterHeaderOut = "" # Def: Global C++ *LUA.h
  528. cppRegisterHeaderOut += "#pragma once\n"
  529. cppRegisterHeaderOut += "#include <%s>\n" % (mainInclude)
  530. cppRegisterHeaderOut += "extern \"C\" {\n"
  531. cppRegisterHeaderOut += "#include <stdio.h>\n"
  532. cppRegisterHeaderOut += "#include \"lua.h\"\n"
  533. cppRegisterHeaderOut += "#include \"lualib.h\"\n"
  534. cppRegisterHeaderOut += "#include \"lauxlib.h\"\n"
  535. cppRegisterHeaderOut += "int _PolyExport luaopen_%s(lua_State *L);\n" % (prefix)
  536. cppRegisterHeaderOut += "}\n"
  537. # Write out global files
  538. mkdir_p(includePath)
  539. mkdir_p(apiPath)
  540. mkdir_p(sourcePath)
  541. fout = open("%s/%sLUA.h" % (includePath, prefix), "w")
  542. fout.write(cppRegisterHeaderOut)
  543. fout = open("%s/%s.lua" % (apiPath, prefix), "w")
  544. fout.write(luaIndexOut)
  545. fout = open("%s/%sLUAWrappers.h" % (includePath, prefix), "w")
  546. fout.write(wrappersHeaderOut)
  547. fout = open("%s/%sLUA.cpp" % (sourcePath, prefix), "w")
  548. fout.write(cppRegisterOut)
  549. # Create .pak zip archive
  550. pattern = '*.lua'
  551. os.chdir(apiPath)
  552. if libName == "Polycore":
  553. with ZipFile("api.pak", 'w') as myzip:
  554. for root, dirs, files in os.walk("."):
  555. for filename in fnmatch.filter(files, pattern):
  556. myzip.write(os.path.join(root, filename))
  557. if len(sys.argv) < 10:
  558. print ("Usage:\n%s [input path] [prefix] [main include] [lib small name] [lib name] [api path] [api class-path] [include path] [source path] [inherit-in-module-file path (optional)]" % (sys.argv[0]))
  559. sys.exit(1)
  560. else:
  561. createLUABindings(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9], sys.argv[10] if len(sys.argv)>10 else None)