create_lua_library.py 40 KB

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