create_lua_library.py 36 KB

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