create_lua_library.py 33 KB

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