Generator.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  1. #include "Generator.h"
  2. Generator* Generator::__instance = NULL;
  3. set<string> __warnings;
  4. // Warning flags.
  5. static bool __printTemplateWarning = false;
  6. static bool __printVarargWarning = false;
  7. static bool __printOperatorWarning = false;
  8. // Utility functions (local to this file).
  9. static string trim(const string& str);
  10. static string stripTypeQualifiers(const string& typeStr, FunctionBinding::Param::Kind& kind);
  11. static inline bool isWantedFileNormal(const string& s);
  12. static inline bool isNamespaceFile(const string& s);
  13. static bool getFileList(string directory, vector<string>& files, bool (*isWantedFile)(const string& s));
  14. static bool isReservedKeyword(string name);
  15. Generator* Generator::getInstance()
  16. {
  17. if (!__instance)
  18. __instance = new Generator();
  19. return __instance;
  20. }
  21. void Generator::releaseInstance()
  22. {
  23. SAFE_DELETE(__instance);
  24. }
  25. string Generator::getUniqueName(string name)
  26. {
  27. // Calculate the unique name for the given identifier (class, struct, enum, etc).
  28. string uniquename = name;
  29. size_t i = uniquename.find("::");
  30. while (i != uniquename.npos)
  31. {
  32. uniquename.replace(i, 2, SCOPE_REPLACEMENT);
  33. i = uniquename.find("::");
  34. }
  35. return uniquename;
  36. }
  37. string Generator::getUniqueNameFromRef(string refId)
  38. {
  39. return getUniqueName(getIdentifier(refId));
  40. }
  41. vector<string> Generator::getScopePath(string classname, string ns)
  42. {
  43. size_t i = classname.find("::");
  44. int index = 0;
  45. vector<string> scopePath;
  46. while (i != classname.npos)
  47. {
  48. string scope = classname.substr(0, i);
  49. if (scope != ns)
  50. scopePath.push_back(scope);
  51. classname = classname.substr(i + 2);
  52. i = classname.find("::");
  53. }
  54. return scopePath;
  55. }
  56. string Generator::getIdentifier(string refId)
  57. {
  58. if (_refIds.find(refId) != _refIds.end())
  59. return _refIds[refId];
  60. return refId;
  61. }
  62. string Generator::getClassNameWithoutNamespace(string classname)
  63. {
  64. size_t index = classname.find("::");
  65. if (index != classname.npos)
  66. {
  67. string ns = classname.substr(0, index);
  68. if (_namespaces.find(ns) != _namespaces.end())
  69. {
  70. string tmp = classname.substr(index + 2);
  71. size_t tmpIndex = tmp.find("::");
  72. if (tmpIndex != tmp.npos)
  73. tmp = tmp.substr(0, tmpIndex);
  74. tmp = ns + string("::") + tmp;
  75. if (find(_namespaces[ns].begin(), _namespaces[ns].end(), tmp) != _namespaces[ns].end())
  76. return classname.substr(index + 2);
  77. }
  78. }
  79. return classname;
  80. }
  81. void Generator::setIdentifier(string refId, string id)
  82. {
  83. _refIds[refId] = id;
  84. }
  85. bool Generator::isDerived(const ClassBinding& c, string classname)
  86. {
  87. for (unsigned int i = 0; i < c.derived.size(); i++)
  88. {
  89. const string& derivedClassName = getIdentifier(c.derived[i]);
  90. if (derivedClassName == classname ||
  91. (_classes.find(derivedClassName) != _classes.end() &&
  92. isDerived(_classes[derivedClassName], classname)))
  93. {
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. bool Generator::isRef(string classname)
  100. {
  101. // Check if the class is derived from Ref.
  102. for (unsigned int i = 0; i < _topLevelBaseClasses.size(); i++)
  103. {
  104. if (_topLevelBaseClasses[i] == REF_CLASS_NAME)
  105. {
  106. return isDerived(_classes[_topLevelBaseClasses[i]], classname);
  107. }
  108. }
  109. return classname == REF_CLASS_NAME;
  110. }
  111. string Generator::getCompoundName(XMLElement* node)
  112. {
  113. // Get the name of the namespace, class, struct, or file that we are processing.
  114. XMLElement* nameElement = node->FirstChildElement("compoundname");
  115. if (!nameElement)
  116. {
  117. GP_ERROR("Missing 'compoundname' child node of 'compounddef' node for XML document '%s'.", _file);
  118. return "";
  119. }
  120. const char* text = nameElement->GetText();
  121. if (!text)
  122. {
  123. GP_ERROR("The 'compoundname' node is empty for XML document '%s'.", _file);
  124. return "";
  125. }
  126. return string(text);
  127. }
  128. void Generator::run(string inDir, string outDir)
  129. {
  130. // Set the output directory.
  131. _outDir = outDir;
  132. // Get a list of the Doxygen XML files that specify a namespace.
  133. // Note: we must do this before adding the normal files so that
  134. // when we process the files sequentially, we process the namespaces
  135. // before the normal files (so that namespaces can be removed
  136. // properly from class/struct names, etc.)
  137. vector<string> files;
  138. getFileList(inDir, files, isNamespaceFile);
  139. // Add all of the normal Doxygen XML files we want to use to generate Lua bindings.
  140. if (!getFileList(inDir, files, isWantedFileNormal) || files.empty())
  141. {
  142. GP_ERROR("Failed to get a valid list of files to generate bindings from using directory '%s'.", inDir.c_str());
  143. return;
  144. }
  145. // Go through each file and build the data needed to generate the bindings.
  146. for (vector<string>::iterator iter = files.begin(); iter != files.end(); iter++)
  147. {
  148. tinyxml2::XMLDocument doc;
  149. _file = iter->c_str();
  150. doc.LoadFile(iter->c_str());
  151. int ret = doc.ErrorID();
  152. if (ret != 0)
  153. {
  154. GP_ERROR("Failed to load XML document '%s' properly with error ID %d.", iter->c_str(), ret);
  155. continue;
  156. }
  157. XMLElement* rootNode = doc.FirstChildElement("doxygen");
  158. if (!rootNode)
  159. {
  160. GP_ERROR("Missing root 'doxygen' node for XML document '%s'.", iter->c_str());
  161. continue;
  162. }
  163. XMLElement* node = rootNode->FirstChildElement("compounddef");
  164. if (!node)
  165. {
  166. GP_ERROR("Missing 'compounddef' node for XML document '%s'.", iter->c_str());
  167. continue;
  168. }
  169. const char* kind = node->Attribute("kind");
  170. if (kind && strcmp(kind, "namespace") == 0)
  171. {
  172. string name = getCompoundName(node);
  173. cout << "Parsing namespace " << name << "...\n";
  174. getNamespace(node, name);
  175. }
  176. else if ((kind && strcmp(kind, "class") == 0 || strcmp(kind, "struct") == 0) &&
  177. strcmp(node->Attribute("prot"), "public") == 0)
  178. {
  179. string name = getCompoundName(node);
  180. cout << "Parsing class/struct " << name << "...\n";
  181. getClass(node, name);
  182. }
  183. else if (kind && strcmp(kind, "file") == 0)
  184. {
  185. string name = getCompoundName(node);
  186. cout << "Parsing file " << name << "...\n";
  187. if (name.find(".h") != name.npos)
  188. {
  189. getFunctions(node);
  190. getEnums(node, name);
  191. }
  192. else if (name.find(".cpp") != name.npos)
  193. {
  194. getIncludes(node, name);
  195. }
  196. }
  197. }
  198. // Resolve all inheritance.
  199. resolveInheritance();
  200. // Resolve all unrecognized parameter and return value types.
  201. resolveTypes();
  202. // Resolve all inherited include files.
  203. resolveInheritedIncludes();
  204. // Generate the script bindings.
  205. generateBindings();
  206. // Print out all warnings (unsupported types, function name-Lua keyword clashes, etc.)
  207. if (__warnings.size() > 0)
  208. {
  209. cout << "\nWarnings:\n";
  210. for (set<string>::iterator iter = __warnings.begin(); iter!= __warnings.end(); iter++)
  211. {
  212. GP_WARN("%s", iter->c_str());
  213. }
  214. }
  215. // Print warnings for the use of unsupported C++ features.
  216. if (__printTemplateWarning)
  217. GP_WARN("Detected the use of template parameters; this feature of C++ is not supported.");
  218. if (__printVarargWarning)
  219. GP_WARN("Detected the use of variable argument lists; this feature of C++ is not supported.");
  220. if (__printOperatorWarning)
  221. GP_WARN("Detected the use of operator overloading; this feature of C++ is not supported.");
  222. }
  223. Generator::Generator()
  224. {
  225. }
  226. Generator::~Generator()
  227. {
  228. }
  229. void Generator::getFunctions(XMLElement* fileNode)
  230. {
  231. // Process all public, non-static functions and variables that are defined in this file.
  232. XMLElement* node = NULL;
  233. const char* kind = NULL;
  234. const char* isStatic = NULL;
  235. for (node = fileNode->FirstChildElement("sectiondef"); node != NULL; node = node->NextSiblingElement("sectiondef"))
  236. {
  237. kind = node->Attribute("kind");
  238. if (kind && strcmp(kind, "func") == 0)
  239. {
  240. XMLElement* e = node->FirstChildElement("memberdef");
  241. while (e)
  242. {
  243. isStatic = e->Attribute("static");
  244. if (e->FirstChildElement("templateparamlist"))
  245. {
  246. __printTemplateWarning = true;
  247. }
  248. else if (getScriptFlag(e) != "ignore" &&
  249. (!isStatic || strcmp(isStatic, "yes") != 0))
  250. {
  251. FunctionBinding b;
  252. b.type = FunctionBinding::GLOBAL_FUNCTION;
  253. b.name = getName(e);
  254. if (!isReservedKeyword(b.name))
  255. {
  256. // Ignore operators.
  257. if (b.name.find("operator") != 0)
  258. {
  259. b.returnParam = getParam(e);
  260. getParams(e, b);
  261. getCreateFlag(e, b);
  262. _functions[b.getFunctionName()].push_back(b);
  263. }
  264. else
  265. {
  266. __printOperatorWarning = true;
  267. }
  268. }
  269. else
  270. {
  271. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  272. }
  273. }
  274. e = e->NextSiblingElement("memberdef");
  275. }
  276. }
  277. else if (kind && strcmp(kind, "var") == 0)
  278. {
  279. XMLElement* e = node->FirstChildElement("memberdef");
  280. while (e)
  281. {
  282. isStatic = e->Attribute("static");
  283. if (getScriptFlag(e) != "ignore" &&
  284. (!isStatic || strcmp(isStatic, "yes") != 0))
  285. {
  286. FunctionBinding b;
  287. if (getIsConstType(e))
  288. b.type = FunctionBinding::GLOBAL_CONSTANT;
  289. else
  290. b.type = FunctionBinding::GLOBAL_VARIABLE;
  291. b.name = getName(e);
  292. if (!isReservedKeyword(b.name))
  293. {
  294. b.returnParam = getParam(e, true);
  295. _functions[b.getFunctionName()].push_back(b);
  296. }
  297. else
  298. {
  299. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  300. }
  301. }
  302. e = e->NextSiblingElement("memberdef");
  303. }
  304. }
  305. }
  306. }
  307. void Generator::getNamespace(XMLElement* nsNode, const string& name)
  308. {
  309. // Skip the 'std' namespace.
  310. if (name == "std")
  311. return;
  312. // Create a list of all classes that are a part of this namespace.
  313. XMLElement* e = nsNode->FirstChildElement("innerclass");
  314. while (e)
  315. {
  316. _namespaces[name].push_back(e->GetText());
  317. e = e->NextSiblingElement("innerclass");
  318. }
  319. // Parse all functions that are directly in this namespace.
  320. getFunctions(nsNode);
  321. // Parse all enums that are directly in this namespace.
  322. getEnums(nsNode, name);
  323. // Parse all typedefs.
  324. getTypedefs(nsNode, name);
  325. e = nsNode->FirstChildElement("");
  326. }
  327. void Generator::getClass(XMLElement* classNode, const string& name)
  328. {
  329. // Check if we should ignore this class.
  330. if (getScriptFlag(classNode) == "ignore")
  331. return;
  332. // Get the ref id for the class.
  333. string refId = classNode->Attribute("id");
  334. // Create the class binding object that we will store the function bindings in (name -> binding).
  335. ClassBinding classBinding(name, refId);
  336. // Store the mapping between the ref id and the class's fully qualified name.
  337. Generator::getInstance()->setIdentifier(refId, classBinding.classname);
  338. // Get the include header for the original class declaration.
  339. XMLElement* includeElement = classNode->FirstChildElement("includes");
  340. if (includeElement)
  341. {
  342. const char* text = includeElement->GetText();
  343. if (!text)
  344. {
  345. GP_ERROR("The 'includes' node is empty (a class must have an include file) for XML document '%s'.", _file);
  346. return;
  347. }
  348. classBinding.include = text;
  349. }
  350. else
  351. {
  352. // See if we are an inner class. If so, attempt to get the include from the root parent class.
  353. size_t index = classBinding.classname.find("::");
  354. if (index != classBinding.classname.npos)
  355. {
  356. string parentClassName = classBinding.classname.substr(0, index);
  357. if (_classes.find(parentClassName) != _classes.end())
  358. classBinding.include = _classes[parentClassName].include;
  359. }
  360. }
  361. // Track whether the class has any pure virtual functions.
  362. bool hasPureVirtual = false;
  363. // Process all public members that are defined in this class.
  364. XMLElement* node = NULL;
  365. const char* kind = NULL;
  366. for (node = classNode->FirstChildElement("sectiondef"); node != NULL; node = node->NextSiblingElement("sectiondef"))
  367. {
  368. kind = node->Attribute("kind");
  369. if (!kind)
  370. {
  371. GP_ERROR("Section definition is missing required 'kind' attribute in XML document '%s'.", _file);
  372. return;
  373. }
  374. // Process public static functions.
  375. if (strcmp(kind, "public-static-func") == 0)
  376. {
  377. XMLElement* e = node->FirstChildElement("memberdef");
  378. while (e)
  379. {
  380. if (e->FirstChildElement("templateparamlist"))
  381. {
  382. __printTemplateWarning = true;
  383. }
  384. else if (getScriptFlag(e) != "ignore")
  385. {
  386. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  387. b.type = FunctionBinding::STATIC_FUNCTION;
  388. b.name = getName(e);
  389. if (!isReservedKeyword(b.name))
  390. {
  391. b.returnParam = getParam(e, false, b.classname);
  392. getParams(e, b);
  393. getCreateFlag(e, b);
  394. classBinding.bindings[b.getFunctionName()].push_back(b);
  395. }
  396. else
  397. {
  398. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  399. }
  400. }
  401. e = e->NextSiblingElement("memberdef");
  402. }
  403. }
  404. // Process public member functions.
  405. else if (strcmp(kind, "public-func") == 0)
  406. {
  407. XMLElement* e = node->FirstChildElement("memberdef");
  408. while (e)
  409. {
  410. if (e->FirstChildElement("templateparamlist"))
  411. {
  412. __printTemplateWarning = true;
  413. }
  414. else if (getScriptFlag(e) != "ignore")
  415. {
  416. if (strcmp(e->Attribute("virt"), "pure-virtual") == 0)
  417. hasPureVirtual = true;
  418. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  419. b.type = FunctionBinding::MEMBER_FUNCTION;
  420. b.name = getName(e);
  421. if (!isReservedKeyword(b.name))
  422. {
  423. // Ignore operators.
  424. if (b.name.find("operator") != 0)
  425. {
  426. b.returnParam = getParam(e, false, b.classname);
  427. if (b.returnParam.type == FunctionBinding::Param::TYPE_CONSTRUCTOR)
  428. {
  429. b.returnParam.info = refId;
  430. b.own = true;
  431. }
  432. getParams(e, b);
  433. getCreateFlag(e, b);
  434. classBinding.bindings[b.getFunctionName()].push_back(b);
  435. }
  436. else
  437. {
  438. __printOperatorWarning = true;
  439. }
  440. }
  441. else
  442. {
  443. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  444. }
  445. }
  446. e = e->NextSiblingElement("memberdef");
  447. }
  448. }
  449. // Process public static variables.
  450. else if (strcmp(kind, "public-static-attrib") == 0)
  451. {
  452. XMLElement* e = node->FirstChildElement("memberdef");
  453. while (e)
  454. {
  455. if (getScriptFlag(e) != "ignore")
  456. {
  457. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  458. if (getIsConstType(e))
  459. b.type = FunctionBinding::STATIC_CONSTANT;
  460. else
  461. b.type = FunctionBinding::STATIC_VARIABLE;
  462. b.name = getName(e);
  463. if (!isReservedKeyword(b.name))
  464. {
  465. b.returnParam = getParam(e, true, b.classname);
  466. classBinding.bindings[b.getFunctionName()].push_back(b);
  467. }
  468. else
  469. {
  470. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  471. }
  472. }
  473. e = e->NextSiblingElement("memberdef");
  474. }
  475. }
  476. // Process public member variables.
  477. else if (strcmp(kind, "public-attrib") == 0)
  478. {
  479. XMLElement* e = node->FirstChildElement("memberdef");
  480. while (e)
  481. {
  482. if (e->FirstChildElement("templateparamlist"))
  483. {
  484. __printTemplateWarning = true;
  485. }
  486. else if (getScriptFlag(e) != "ignore")
  487. {
  488. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  489. if (getIsConstType(e))
  490. b.type = FunctionBinding::MEMBER_CONSTANT;
  491. else
  492. b.type = FunctionBinding::MEMBER_VARIABLE;
  493. b.name = getName(e);
  494. if (!isReservedKeyword(b.name))
  495. {
  496. b.returnParam = getParam(e, true, b.classname);
  497. classBinding.bindings[b.getFunctionName()].push_back(b);
  498. }
  499. else
  500. {
  501. __warnings.insert(string("Function name '") + b.name + string("' is a reserved Lua keyword; binding '") + b.getFunctionName() + string("' was not generated."));
  502. }
  503. }
  504. e = e->NextSiblingElement("memberdef");
  505. }
  506. }
  507. else if (strcmp(kind, "protected-func") == 0 ||
  508. strcmp(kind, "private-func") == 0)
  509. {
  510. // Check for inaccessible constructor/destructor
  511. // and create a list of all other inaccessible functions
  512. // (we do this so that classes that override a public function
  513. // and change its scope to protected or private work properly
  514. // from Lua-i.e. no binding is generated for such functions).
  515. XMLElement* e = node->FirstChildElement("memberdef");
  516. while (e)
  517. {
  518. if (strcmp(e->Attribute("virt"), "pure-virtual") == 0)
  519. hasPureVirtual = true;
  520. FunctionBinding::Param t = getParam(e);
  521. if (t.type == FunctionBinding::Param::TYPE_CONSTRUCTOR)
  522. {
  523. classBinding.inaccessibleConstructor = true;
  524. }
  525. else if (t.type == FunctionBinding::Param::TYPE_DESTRUCTOR)
  526. {
  527. classBinding.inaccessibleDestructor = true;
  528. }
  529. else
  530. {
  531. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  532. b.type = FunctionBinding::MEMBER_FUNCTION;
  533. b.name = getName(e);
  534. if (!isReservedKeyword(b.name))
  535. {
  536. // Ignore operators.
  537. if (b.name.find("operator") != 0)
  538. {
  539. b.returnParam = getParam(e, false, b.classname);
  540. if (b.returnParam.type == FunctionBinding::Param::TYPE_CONSTRUCTOR)
  541. {
  542. b.returnParam.info = refId;
  543. b.own = true;
  544. }
  545. getParams(e, b);
  546. getCreateFlag(e, b);
  547. classBinding.hidden[b.getFunctionName()].push_back(b);
  548. }
  549. else
  550. {
  551. __printOperatorWarning = true;
  552. }
  553. }
  554. }
  555. e = e->NextSiblingElement("memberdef");
  556. }
  557. }
  558. else if (strcmp(kind, "protected-static-func") == 0 ||
  559. strcmp(kind, "private-static-func") == 0)
  560. {
  561. // Create a list of all other inaccessible functions
  562. // (we do this so that classes that override a public function
  563. // and change its scope to protected or private work properly
  564. // from Lua-i.e. no binding is generated for such functions).
  565. XMLElement* e = node->FirstChildElement("memberdef");
  566. while (e)
  567. {
  568. if (e->FirstChildElement("templateparamlist"))
  569. {
  570. __printTemplateWarning = true;
  571. }
  572. else if (getScriptFlag(e) != "ignore")
  573. {
  574. FunctionBinding b(classBinding.classname, classBinding.uniquename);
  575. b.type = FunctionBinding::STATIC_FUNCTION;
  576. b.name = getName(e);
  577. if (!isReservedKeyword(b.name))
  578. {
  579. b.returnParam = getParam(e, false, b.classname);
  580. getParams(e, b);
  581. getCreateFlag(e, b);
  582. classBinding.hidden[b.getFunctionName()].push_back(b);
  583. }
  584. }
  585. e = e->NextSiblingElement("memberdef");
  586. }
  587. }
  588. // Process public enums and typedefs.
  589. else if (strcmp(kind, "public-type") == 0)
  590. {
  591. XMLElement* e = node->FirstChildElement("memberdef");
  592. while (e)
  593. {
  594. if (getScriptFlag(e) != "ignore")
  595. {
  596. if (strcmp(e->Attribute("kind"), "enum") == 0)
  597. {
  598. getEnum(e, classBinding.classname, classBinding.ns, classBinding.include);
  599. }
  600. else if (strcmp(e->Attribute("kind"), "typedef") == 0)
  601. {
  602. getTypedef(e, classBinding.classname, classBinding.ns);
  603. }
  604. }
  605. e = e->NextSiblingElement("memberdef");
  606. }
  607. }
  608. else
  609. {
  610. // Ignore other section definitions.
  611. }
  612. }
  613. // If the class has a pure-virtual method, we mark the constructor as inaccessible
  614. // and remove any constructor bindings that are in the list.
  615. if (hasPureVirtual)
  616. {
  617. classBinding.inaccessibleConstructor = true;
  618. map<string, vector<FunctionBinding> >::iterator iter = classBinding.bindings.begin();
  619. for (; iter != classBinding.bindings.end(); iter++)
  620. {
  621. if (iter->second[0].returnParam.type == FunctionBinding::Param::TYPE_CONSTRUCTOR)
  622. {
  623. classBinding.bindings.erase(iter);
  624. break;
  625. }
  626. }
  627. }
  628. // Store the class's derived class(es)' ref id(s) if it has any.
  629. node = classNode->FirstChildElement("derivedcompoundref");
  630. while (node)
  631. {
  632. classBinding.derived.push_back(node->Attribute("refid"));
  633. node = node->NextSiblingElement("derivedcompoundref");
  634. }
  635. // If the class has no base classes and it has derived classes, add it to the list of top-level classes.
  636. if (!classNode->FirstChildElement("basecompoundref") && classBinding.derived.size() > 0)
  637. _topLevelBaseClasses.push_back(classBinding.classname);
  638. // Insert the class binding into the global table.
  639. _classes[classBinding.classname] = classBinding;
  640. }
  641. void Generator::getEnums(XMLElement* fileNode, string ns)
  642. {
  643. XMLElement* node = NULL;
  644. const char* kind = NULL;
  645. for (node = fileNode->FirstChildElement("sectiondef"); node != NULL; node = node->NextSiblingElement("sectiondef"))
  646. {
  647. kind = node->Attribute("kind");
  648. if (!kind)
  649. {
  650. GP_ERROR("Section definition is missing required 'kind' attribute in XML document '%s'.", _file);
  651. return;
  652. }
  653. // Process the enums.
  654. if (strcmp(kind, "enum") == 0)
  655. {
  656. XMLElement* e = node->FirstChildElement("memberdef");
  657. while (e)
  658. {
  659. if (getScriptFlag(e) != "ignore" && strcmp(e->Attribute("kind"), "enum") == 0)
  660. {
  661. getEnum(e, "", ns);
  662. }
  663. e = e->NextSiblingElement("memberdef");
  664. }
  665. }
  666. }
  667. }
  668. void Generator::getEnum(XMLElement* e, string classname, string ns, string include)
  669. {
  670. // Get the enumeration's name.
  671. string enumname = classname;
  672. if (enumname.size() > 0)
  673. enumname += string("::");
  674. enumname += getName(e);
  675. // Get the ref id for the enum.
  676. string refId = e->Attribute("id");
  677. // Store the ref id to name mapping.
  678. Generator::getInstance()->setIdentifier(refId, enumname);
  679. // Add the enum to the enum list if it's not there
  680. // (we implicitly create it when we set its scope path).
  681. if (_enums.find(enumname) == _enums.end())
  682. _enums[enumname].scopePath = Generator::getScopePath(enumname, ns);
  683. // Set the include file for the enum.
  684. if (include.size() > 0)
  685. _enums[enumname].include = include;
  686. else
  687. {
  688. XMLElement* location = e->FirstChildElement("location");
  689. if (location)
  690. _enums[enumname].include = location->Attribute("file");
  691. }
  692. for (e = e->FirstChildElement("enumvalue"); e; e = e->NextSiblingElement("enumvalue"))
  693. {
  694. _enums[enumname].values.push_back(getName(e));
  695. }
  696. }
  697. void Generator::getTypedefs(XMLElement* fileNode, string ns)
  698. {
  699. XMLElement* node = NULL;
  700. const char* kind = NULL;
  701. for (node = fileNode->FirstChildElement("sectiondef"); node != NULL; node = node->NextSiblingElement("sectiondef"))
  702. {
  703. kind = node->Attribute("kind");
  704. if (!kind)
  705. {
  706. GP_ERROR("Section definition is missing required 'kind' attribute in XML document '%s'.", _file);
  707. return;
  708. }
  709. // Process the enums.
  710. if (strcmp(kind, "typedef") == 0)
  711. {
  712. XMLElement* e = node->FirstChildElement("memberdef");
  713. while (e)
  714. {
  715. if (getScriptFlag(e) != "ignore" && strcmp(e->Attribute("kind"), "typedef") == 0)
  716. {
  717. getTypedef(e, "", ns);
  718. }
  719. e = e->NextSiblingElement("memberdef");
  720. }
  721. }
  722. }
  723. }
  724. void Generator::getTypedef(XMLElement* e, string classname, string ns)
  725. {
  726. TypedefBinding t;
  727. // Get the typedef's name.
  728. string tname = classname;
  729. if (tname.size() > 0)
  730. tname += string("::");
  731. tname += getName(e);
  732. if (!REMOVE_NAMESPACE)
  733. tname = ns + string("::") + tname;
  734. // Get the typedef's id and store the mapping from ref id to name.
  735. string refId = e->Attribute("id");
  736. setIdentifier(refId, tname);
  737. FunctionBinding::Param p = getParam(e);
  738. if (p.info.size() > 0)
  739. t.refId = p.info;
  740. _typedefs[tname] = t;
  741. }
  742. static inline bool getScriptFlagHelper(XMLElement* e, string& flag)
  743. {
  744. XMLElement* x = e->FirstChildElement("xmlonly");
  745. if (x)
  746. {
  747. flag = x->GetText();
  748. return true;
  749. }
  750. x = e->FirstChild() ? e->FirstChild()->ToElement() : NULL;
  751. while (x)
  752. {
  753. if (getScriptFlagHelper(x, flag))
  754. return true;
  755. x = x->NextSibling() ? x->NextSibling()->ToElement() : NULL;
  756. }
  757. return false;
  758. }
  759. string Generator::getScriptFlag(XMLElement* e)
  760. {
  761. string flag;
  762. XMLElement* n = e->FirstChildElement("detaileddescription");
  763. if (n)
  764. getScriptFlagHelper(n, flag);
  765. return flag;
  766. }
  767. void Generator::getCreateFlag(XMLElement* e, FunctionBinding& b)
  768. {
  769. if (getScriptFlag(e) == "create")
  770. b.own = true;
  771. }
  772. string Generator::getName(XMLElement* e)
  773. {
  774. // Get the name for the binding.
  775. XMLElement* nameElement = e->FirstChildElement("name");
  776. if (!nameElement)
  777. {
  778. GP_ERROR("Missing 'name' child node in XML document '%s'.", _file);
  779. return string();
  780. }
  781. return nameElement->GetText();
  782. }
  783. bool Generator::getIsConstType(XMLElement* e)
  784. {
  785. XMLElement* typeElement = e->FirstChildElement("type");
  786. if (!typeElement)
  787. {
  788. GP_ERROR("Missing 'type' node in XML document '%s'.", _file);
  789. return false;
  790. }
  791. XMLNode* textNode = typeElement->FirstChild();
  792. if (textNode)
  793. {
  794. XMLText* text = textNode->ToText();
  795. if (text)
  796. {
  797. string type = text->Value();
  798. return type.find("const") != type.npos;
  799. }
  800. }
  801. return false;
  802. }
  803. FunctionBinding::Param Generator::getParam(XMLElement* e, bool isVariable, string classname)
  804. {
  805. // Get the type for the current element (either the return type or a parameter type).
  806. XMLElement* typeElement = e->FirstChildElement("type");
  807. if (!typeElement)
  808. {
  809. GP_ERROR("Missing 'type' node in XML document '%s'.", _file);
  810. }
  811. FunctionBinding::Param p;
  812. XMLNode* textNode = typeElement->FirstChild();
  813. if (!textNode)
  814. {
  815. // Get the name of the current element to see if it is a destructor.
  816. string name = getName(e);
  817. if (name.find("~") == 0)
  818. {
  819. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_DESTRUCTOR);
  820. }
  821. else
  822. {
  823. // Assume it's a constructor.
  824. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_CONSTRUCTOR, FunctionBinding::Param::KIND_POINTER, name);
  825. }
  826. }
  827. else
  828. {
  829. // Get the type string without const or reference qualifiers (and trim whitespace).
  830. string refId = "";
  831. string typeStr = "";
  832. FunctionBinding::Param::Kind kind;
  833. {
  834. // Attempt to process the type as reference (i.e. class, struct, enum, typedef, etc.) type.
  835. XMLNode* node = textNode;
  836. while (node)
  837. {
  838. if (strcmp(node->Value(), "ref") == 0)
  839. {
  840. refId = node->ToElement()->Attribute("refid");
  841. typeStr += node->ToElement()->GetText();
  842. }
  843. else if (node->ToText())
  844. {
  845. typeStr += node->ToText()->Value();
  846. }
  847. node = node->NextSibling();
  848. }
  849. typeStr = stripTypeQualifiers(typeStr, kind);
  850. }
  851. if (typeStr == "void")
  852. {
  853. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_VOID, kind);
  854. }
  855. else if (typeStr == "bool")
  856. {
  857. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_BOOL, kind);
  858. }
  859. else if (typeStr == "char" && kind != FunctionBinding::Param::KIND_POINTER)
  860. {
  861. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_CHAR, kind);
  862. }
  863. else if (typeStr == "short")
  864. {
  865. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_SHORT, kind);
  866. }
  867. else if (typeStr == "int")
  868. {
  869. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_INT, kind);
  870. }
  871. else if (typeStr == "long")
  872. {
  873. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_LONG, kind);
  874. }
  875. else if (typeStr == "unsigned char")
  876. {
  877. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_UCHAR, kind);
  878. }
  879. else if (typeStr == "unsigned short")
  880. {
  881. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_USHORT, kind);
  882. }
  883. else if (typeStr == "unsigned int")
  884. {
  885. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_UINT, kind);
  886. }
  887. else if (typeStr == "unsigned long")
  888. {
  889. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_ULONG, kind);
  890. }
  891. else if (typeStr == "float")
  892. {
  893. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_FLOAT, kind);
  894. }
  895. else if (typeStr == "double")
  896. {
  897. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_DOUBLE, kind);
  898. }
  899. else if (typeStr == "string" || typeStr == "std::string")
  900. {
  901. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_STRING, kind, "string");
  902. }
  903. else if (typeStr == "char" && kind == FunctionBinding::Param::KIND_POINTER)
  904. {
  905. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_STRING, kind, "char*");
  906. }
  907. else if (_enums.find(typeStr) != _enums.end() ||
  908. (classname.size() > 0 && _enums.find(classname + string("::") + typeStr) != _enums.end()))
  909. {
  910. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_ENUM, kind, refId);
  911. }
  912. else if (typeStr == "...")
  913. {
  914. __printVarargWarning = true;
  915. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_VARARGS);
  916. }
  917. else
  918. {
  919. p = FunctionBinding::Param(FunctionBinding::Param::TYPE_UNRECOGNIZED, kind, (refId.size() > 0) ? refId : typeStr);
  920. }
  921. // Check if the type is a pointer declared with square brackets (i.e. float x[4]).
  922. XMLElement* arrayElement = NULL;
  923. if ((arrayElement = e->FirstChildElement("array")) != NULL ||
  924. (isVariable && (arrayElement = e->FirstChildElement("argsstring")) != NULL))
  925. {
  926. const char* text = arrayElement->GetText();
  927. string arrayString = (text ? text : "");
  928. string::size_type i = arrayString.find("[");
  929. string::size_type k = arrayString.find("]");
  930. if (i != arrayString.npos && k != arrayString.npos)
  931. {
  932. p.kind = FunctionBinding::Param::KIND_POINTER;
  933. if (i != k - 1)
  934. p.info = arrayString.substr(i + 1, k - (i + 1));
  935. }
  936. }
  937. }
  938. // Get the default value for the parameter if it has one.
  939. XMLElement* defaultValueElement = e->FirstChildElement("defval");
  940. if (defaultValueElement)
  941. {
  942. p.hasDefaultValue = true;
  943. }
  944. return p;
  945. }
  946. void Generator::getParams(XMLElement* e, FunctionBinding& b)
  947. {
  948. XMLElement* param = e->FirstChildElement("param");
  949. while (param)
  950. {
  951. FunctionBinding::Param p = getParam(param, false, b.classname);
  952. if (p.type != FunctionBinding::Param::TYPE_VARARGS)
  953. b.paramTypes.push_back(p);
  954. param = param->NextSiblingElement("param");
  955. }
  956. }
  957. void Generator::resolveMembers(const ClassBinding& c)
  958. {
  959. vector<ClassBinding*> derived;
  960. // Go through the derived classes' bindings and update them.
  961. ClassBinding* cb = NULL;
  962. map<string, vector<FunctionBinding> >::const_iterator iter;
  963. for (unsigned int i = 0; i < c.derived.size(); i++)
  964. {
  965. // If the class is not in the map of classes, then
  966. // it was marked to be ignored, so skip over it.
  967. string derivedClassName = getIdentifier(c.derived[i]);
  968. if (_classes.find(derivedClassName) == _classes.end())
  969. continue;
  970. cb = &_classes[derivedClassName];
  971. // Go through this class' bindings and add them to the current
  972. // derived class if they are not already there (excluding constructors and destructors).
  973. for (iter = c.bindings.begin(); iter != c.bindings.end(); iter++)
  974. {
  975. FunctionBinding b(cb->classname, cb->uniquename);
  976. b.type = iter->second[0].type;
  977. b.name = iter->second[0].name;
  978. map<string, vector<FunctionBinding> >::iterator findIter = cb->bindings.find(b.getFunctionName());
  979. map<string, vector<FunctionBinding> >::iterator hiddenIter = cb->hidden.find(b.getFunctionName());
  980. if (findIter == cb->bindings.end() && hiddenIter == cb->hidden.end())
  981. {
  982. for (unsigned int i = 0, iCount = iter->second.size(); i < iCount; i++)
  983. {
  984. if (iter->second[i].returnParam.type != FunctionBinding::Param::TYPE_CONSTRUCTOR &&
  985. iter->second[i].returnParam.type != FunctionBinding::Param::TYPE_DESTRUCTOR)
  986. {
  987. // Copy the binding, but set its function name to
  988. // empty so that it is regenerated correctly.
  989. b = iter->second[i];
  990. b.functionName = "";
  991. b.classname = cb->classname;
  992. b.uniquename = cb->uniquename;
  993. cb->bindings[b.getFunctionName()].push_back(b);
  994. }
  995. }
  996. }
  997. else
  998. {
  999. bool addBinding;
  1000. for (unsigned int i = 0, iCount = iter->second.size(); i < iCount; i++)
  1001. {
  1002. string name = iter->second[i].name;
  1003. addBinding = true;
  1004. if (findIter != cb->bindings.end())
  1005. {
  1006. for (unsigned int j = 0, jCount = findIter->second.size(); j < jCount; j++)
  1007. {
  1008. if (FunctionBinding::signaturesMatch(iter->second[i], findIter->second[j]))
  1009. {
  1010. addBinding = false;
  1011. break;
  1012. }
  1013. }
  1014. // To call the base function, we have to qualify the call since
  1015. // the derived class has a function with the same name and different parameters.
  1016. if (addBinding)
  1017. name = iter->second[i].classname + string("::") + iter->second[i].name;
  1018. }
  1019. if (hiddenIter != cb->hidden.end())
  1020. {
  1021. for (unsigned int j = 0, jCount = hiddenIter->second.size(); j < jCount; j++)
  1022. {
  1023. if (FunctionBinding::signaturesMatch(iter->second[i], hiddenIter->second[j]))
  1024. {
  1025. addBinding = false;
  1026. break;
  1027. }
  1028. }
  1029. }
  1030. if (addBinding)
  1031. {
  1032. FunctionBinding b = iter->second[i];
  1033. b.name = name;
  1034. b.functionName = findIter->first;
  1035. b.classname = cb->classname;
  1036. b.uniquename = getUniqueName(cb->classname);
  1037. if (findIter != cb->bindings.end())
  1038. findIter->second.push_back(b);
  1039. else
  1040. cb->bindings[b.getFunctionName()].push_back(b);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. derived.push_back(cb);
  1046. }
  1047. // Go through the derived classes' bindings and resolve the members for their derived classes.
  1048. for (unsigned int i = 0; i < derived.size(); i++)
  1049. {
  1050. resolveMembers(*derived[i]);
  1051. }
  1052. }
  1053. void Generator::resolveInheritance()
  1054. {
  1055. // Go through the class inheritance tree and update each class's bindings list
  1056. // to include the bindings from the base class that haven't been overridden.
  1057. for (unsigned int i = 0; i < _topLevelBaseClasses.size(); i++)
  1058. {
  1059. resolveMembers(_classes[_topLevelBaseClasses[i]]);
  1060. }
  1061. }
  1062. void Generator::resolveIncludes(const ClassBinding& c)
  1063. {
  1064. vector<ClassBinding*> derived;
  1065. // Go through the derived classes' bindings and update them.
  1066. ClassBinding* cb = NULL;
  1067. map<string, vector<FunctionBinding> >::const_iterator iter;
  1068. for (unsigned int i = 0; i < c.derived.size(); i++)
  1069. {
  1070. // If the class is not in the map of classes, then
  1071. // it was marked to be ignored, so skip over it.
  1072. string derivedClassName = getIdentifier(c.derived[i]);
  1073. if (_classes.find(derivedClassName) == _classes.end())
  1074. continue;
  1075. cb = &_classes[derivedClassName];
  1076. // Add all include files (uniquely) from the base class to the derived class.
  1077. map<string, set<string> >::iterator baseIncludes = _includes.find(c.include);
  1078. if (baseIncludes != _includes.end() && baseIncludes->second.size() > 0)
  1079. {
  1080. set<string>::iterator iter = baseIncludes->second.begin();
  1081. set<string>& derivedIncludes = _includes[cb->include];
  1082. for (; iter != baseIncludes->second.end(); iter++)
  1083. {
  1084. derivedIncludes.insert(*iter);
  1085. }
  1086. }
  1087. derived.push_back(cb);
  1088. }
  1089. // Go through the derived classes' bindings and resolve the members for their derived classes.
  1090. for (unsigned int i = 0; i < derived.size(); i++)
  1091. {
  1092. resolveIncludes(*derived[i]);
  1093. }
  1094. }
  1095. void Generator::resolveInheritedIncludes()
  1096. {
  1097. // Go through the class inheritance tree and update each class's
  1098. // list of includes to include the includes from the base class
  1099. for (unsigned int i = 0; i < _topLevelBaseClasses.size(); i++)
  1100. {
  1101. resolveIncludes(_classes[_topLevelBaseClasses[i]]);
  1102. }
  1103. }
  1104. void Generator::resolveType(FunctionBinding::Param* param, string functionName, string header)
  1105. {
  1106. string name = getIdentifier(param->info);
  1107. if (param->type == FunctionBinding::Param::TYPE_UNRECOGNIZED)
  1108. {
  1109. map<string, TypedefBinding>::iterator typedefIter = _typedefs.find(name);
  1110. if (typedefIter != _typedefs.end() && typedefIter->second.refId.size() > 0)
  1111. {
  1112. param->type = FunctionBinding::Param::TYPE_OBJECT;
  1113. param->info = typedefIter->second.refId;
  1114. }
  1115. else
  1116. {
  1117. map<string, ClassBinding>::iterator classIter = _classes.find(name);
  1118. if (classIter != _classes.end())
  1119. {
  1120. param->type = FunctionBinding::Param::TYPE_OBJECT;
  1121. }
  1122. else
  1123. {
  1124. map<string, EnumBinding>::iterator enumIter = _enums.find(name);
  1125. if (enumIter != _enums.end())
  1126. {
  1127. param->type = FunctionBinding::Param::TYPE_ENUM;
  1128. }
  1129. else
  1130. {
  1131. __warnings.insert(string("Unrecognized C++ type: ") + functionName + string(" -- ") + (name.size() > 0 ? name : param->info));
  1132. }
  1133. }
  1134. }
  1135. }
  1136. // Ensure that the header for the Lua enum conversion
  1137. // functions is included in the file containing the
  1138. // generated binding that this param/return value is part of.
  1139. if (param->type == FunctionBinding::Param::TYPE_ENUM)
  1140. {
  1141. string enumHeader = string("lua_") + getUniqueName(name) + string(".h");
  1142. if (_includes.find(header) != _includes.end())
  1143. {
  1144. set<string>& includes = _includes[header];
  1145. if (includes.find(enumHeader) == includes.end())
  1146. includes.insert(enumHeader);
  1147. }
  1148. else
  1149. {
  1150. _includes[header].insert(enumHeader);
  1151. }
  1152. }
  1153. }
  1154. void Generator::resolveTypes()
  1155. {
  1156. // Go through all member functions and attempt to resolve unrecognized types.
  1157. for (map<string, ClassBinding>::iterator iter = _classes.begin(); iter != _classes.end(); iter++)
  1158. {
  1159. map<string, vector<FunctionBinding> >::iterator functionNameIter = iter->second.bindings.begin();
  1160. for (; functionNameIter != iter->second.bindings.end(); functionNameIter++)
  1161. {
  1162. vector<FunctionBinding>::iterator functionIter = functionNameIter->second.begin();
  1163. for (; functionIter != functionNameIter->second.end(); functionIter++)
  1164. {
  1165. resolveType(&functionIter->returnParam, iter->first + string("::") + functionIter->name, iter->second.include);
  1166. vector<FunctionBinding::Param>::iterator paramIter = functionIter->paramTypes.begin();
  1167. for (; paramIter != functionIter->paramTypes.end(); paramIter++)
  1168. {
  1169. resolveType(&(*paramIter), iter->first + string("::") + functionIter->name, iter->second.include);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. // Go through all non-member functions and attempt to resolve unrecognized types.
  1175. string globalHeader = string("lua_") + string(LUA_GLOBAL_FILENAME) + string(".h");
  1176. for (map<string, vector<FunctionBinding> >::iterator iter = _functions.begin(); iter != _functions.end(); iter++)
  1177. {
  1178. vector<FunctionBinding>::iterator functionIter = iter->second.begin();
  1179. for (; functionIter != iter->second.end(); functionIter++)
  1180. {
  1181. resolveType(&functionIter->returnParam, functionIter->name, globalHeader);
  1182. vector<FunctionBinding::Param>::iterator paramIter = functionIter->paramTypes.begin();
  1183. for (; paramIter != functionIter->paramTypes.end(); paramIter++)
  1184. {
  1185. resolveType(&(*paramIter), functionIter->name, globalHeader);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. void Generator::generateBindings()
  1191. {
  1192. string* bindingNS = new string("gameplay");
  1193. ofstream luaAllH(_outDir + string(LUA_ALL_BINDINGS_FILENAME) + string(".h"));
  1194. string includeGuard = string(LUA_ALL_BINDINGS_FILENAME) + string("_H_");
  1195. transform(includeGuard.begin(), includeGuard.end(), includeGuard.begin(), ::toupper);
  1196. luaAllH << "#ifndef " << includeGuard << "\n";
  1197. luaAllH << "#define " << includeGuard << "\n\n";
  1198. ofstream luaAllCpp(_outDir + string(LUA_ALL_BINDINGS_FILENAME) + string(".cpp"));
  1199. luaAllCpp << "#include \"Base.h\"\n";
  1200. luaAllCpp << "#include \"" << string(LUA_ALL_BINDINGS_FILENAME) << ".h\"\n\n";
  1201. if (bindingNS)
  1202. {
  1203. luaAllCpp << "namespace " << *bindingNS << "\n";
  1204. luaAllCpp << "{\n\n";
  1205. }
  1206. luaAllCpp << "void lua_RegisterAllBindings()\n";
  1207. luaAllCpp << "{\n";
  1208. // Write out all the class bindings.
  1209. if (_classes.size() > 0)
  1210. {
  1211. map<string, ClassBinding>::iterator iter = _classes.begin();
  1212. for (; iter != _classes.end(); iter++)
  1213. {
  1214. cout << "Generating bindings for '" << iter->first << "'...\n";
  1215. iter->second.write(_outDir, _includes[iter->second.include], bindingNS);
  1216. luaAllH << "#include \"lua_" << iter->second.uniquename << ".h\"\n";
  1217. luaAllCpp << " luaRegister_" << iter->second.uniquename << "();\n";
  1218. }
  1219. }
  1220. // Go through all the classes and if they have any derived classes, add them to the list of base classes.
  1221. vector<string> baseClasses;
  1222. for (map<string, ClassBinding>::iterator iter = _classes.begin(); iter != _classes.end(); iter++)
  1223. {
  1224. if (iter->second.derived.size() > 0)
  1225. baseClasses.push_back(iter->first);
  1226. }
  1227. // Write out all the enum files.
  1228. if (_enums.size() > 0)
  1229. {
  1230. // Write out the enum conversion function declarations.
  1231. for (map<string, EnumBinding>::iterator iter = _enums.begin(); iter != _enums.end(); iter++)
  1232. {
  1233. // Header.
  1234. ofstream enumH(_outDir + string("lua_") + getUniqueName(iter->first) + string(".h"));
  1235. includeGuard = string("lua_") + getUniqueName(iter->first) + string("_H_");
  1236. transform(includeGuard.begin(), includeGuard.end(), includeGuard.begin(), ::toupper);
  1237. enumH << "#ifndef " << includeGuard << "\n";
  1238. enumH << "#define " << includeGuard << "\n\n";
  1239. enumH << "#include \"" << iter->second.include << "\"\n\n";
  1240. if (bindingNS)
  1241. {
  1242. enumH << "namespace " << *bindingNS << "\n";
  1243. enumH << "{\n\n";
  1244. }
  1245. enumH << "// Lua bindings for enum conversion functions for " << iter->first << ".\n";
  1246. enumH << iter->first << " lua_enumFromString_" << getUniqueName(iter->first) << "(const char* s);\n";
  1247. enumH << "const char* lua_stringFromEnum_" << getUniqueName(iter->first) << "(" << iter->first << " e);\n\n";
  1248. if (bindingNS)
  1249. {
  1250. enumH << "}\n\n";
  1251. }
  1252. enumH << "#endif\n";
  1253. enumH.close();
  1254. // Implementation.
  1255. ofstream enumCpp(_outDir + string("lua_") + getUniqueName(iter->first) + string(".cpp"));
  1256. enumCpp << "#include \"Base.h\"\n";
  1257. enumCpp << "#include \"lua_" << getUniqueName(iter->first) << ".h\"\n\n";
  1258. if (bindingNS)
  1259. {
  1260. enumCpp << "namespace " << *bindingNS << "\n";
  1261. enumCpp << "{\n\n";
  1262. }
  1263. enumCpp << "static const char* enumStringEmpty = \"\";\n\n";
  1264. // Build the scope string if applicable.
  1265. string scope;
  1266. if (iter->second.scopePath.size() > 0)
  1267. {
  1268. for (unsigned int i = 0; i < iter->second.scopePath.size(); i++)
  1269. {
  1270. scope += iter->second.scopePath[i] + string("::");
  1271. }
  1272. }
  1273. // Write out the string constants that correspond to the enumeration values.
  1274. for (unsigned int i = 0; i < iter->second.values.size(); i++)
  1275. {
  1276. enumCpp << "static const char* luaEnumString_" << getUniqueName(iter->first) << "_";
  1277. enumCpp << iter->second.values[i] << " = \"" << iter->second.values[i] << "\";\n";
  1278. }
  1279. enumCpp << "\n";
  1280. enumCpp << iter->first << " lua_enumFromString_" << getUniqueName(iter->first) << "(const char* s)\n";
  1281. enumCpp << "{\n";
  1282. for (unsigned int i = 0; i < iter->second.values.size(); i++)
  1283. {
  1284. enumCpp << " ";
  1285. enumCpp << "if (strcmp(s, luaEnumString_" << getUniqueName(iter->first) << "_" << iter->second.values[i] << ") == 0)\n";
  1286. enumCpp << " return ";
  1287. if (scope.size() > 0)
  1288. enumCpp << scope;
  1289. enumCpp << iter->second.values[i] << ";\n";
  1290. if (i == iter->second.values.size() - 1)
  1291. {
  1292. enumCpp << " GP_ERROR(\"Invalid enumeration value '%s' for enumeration " << iter->first << ".\", s);\n";
  1293. enumCpp << " return ";
  1294. if (scope.size() > 0)
  1295. enumCpp << scope;
  1296. enumCpp << iter->second.values[0] << ";\n";
  1297. }
  1298. }
  1299. enumCpp << "}\n\n";
  1300. enumCpp << "const char* lua_stringFromEnum_" << getUniqueName(iter->first) << "(" << iter->first << " e)\n";
  1301. enumCpp << "{\n";
  1302. // Write out the enum-to-string conversion code.
  1303. for (unsigned int i = 0; i < iter->second.values.size(); i++)
  1304. {
  1305. enumCpp << " ";
  1306. enumCpp << "if (e == ";
  1307. if (scope.size() > 0)
  1308. enumCpp << scope;
  1309. enumCpp << iter->second.values[i] << ")\n";
  1310. enumCpp << " return luaEnumString_" << getUniqueName(iter->first) << "_" << iter->second.values[i] << ";\n";
  1311. if (i == iter->second.values.size() - 1)
  1312. {
  1313. enumCpp << " GP_ERROR(\"Invalid enumeration value '%d' for enumeration " << iter->first << ".\", e);\n";
  1314. enumCpp << " return enumStringEmpty;\n";
  1315. }
  1316. }
  1317. enumCpp << "}\n\n";
  1318. if (bindingNS)
  1319. {
  1320. enumCpp << "}\n\n";
  1321. }
  1322. enumCpp.close();
  1323. }
  1324. }
  1325. // Write out the global bindings file.
  1326. cout << "Generating global bindings...\n";
  1327. if (baseClasses.size() > 0 || _functions.size() > 0 || _enums.size() > 0)
  1328. {
  1329. // Write out the header file.
  1330. {
  1331. string path = _outDir + string(LUA_GLOBAL_FILENAME) + string(".h");
  1332. ofstream global(path);
  1333. if (!global)
  1334. {
  1335. GP_ERROR("Failed to open file '%s' for generating Lua bindings.", path.c_str());
  1336. goto end;
  1337. }
  1338. includeGuard = string(LUA_GLOBAL_FILENAME) + string("_H_");
  1339. transform(includeGuard.begin(), includeGuard.end(), includeGuard.begin(), ::toupper);
  1340. global << "#ifndef " << includeGuard << "\n";
  1341. global << "#define " << includeGuard << "\n\n";
  1342. // Write out the needed includes for the global enumeration function.
  1343. for (map<string, EnumBinding>::iterator iter = _enums.begin(); iter != _enums.end(); iter++)
  1344. {
  1345. global << "#include \"lua_" << getUniqueName(iter->first) << ".h\"\n";
  1346. }
  1347. global << "\n";
  1348. luaAllH << "#include \"" << string(LUA_GLOBAL_FILENAME) << ".h\"\n";
  1349. luaAllCpp << " luaRegister_" << LUA_GLOBAL_FILENAME << "();\n";
  1350. if (bindingNS)
  1351. {
  1352. global << "namespace " << *bindingNS << "\n";
  1353. global << "{\n\n";
  1354. }
  1355. if (_functions.size() > 0)
  1356. {
  1357. global << "// Lua bindings for global functions.\n";
  1358. // Write out the binding function declarations.
  1359. for (map<string, vector<FunctionBinding> >::iterator iter = _functions.begin(); iter != _functions.end(); iter++)
  1360. {
  1361. global << "int " << iter->second[0].getFunctionName() << "(lua_State* state);\n";
  1362. }
  1363. global << "\n";
  1364. }
  1365. if (_enums.size() > 0)
  1366. {
  1367. global << "// Global enum to string conversion function (used to pass enums to Lua from C++).\n";
  1368. global << "const char* lua_stringFromEnumGlobal(std::string& enumname, unsigned int value);\n\n";
  1369. }
  1370. // Write out the signature of the function used to register the global functions with Lua.
  1371. global << "void luaRegister_" << LUA_GLOBAL_FILENAME << "();\n\n";
  1372. if (bindingNS)
  1373. global << "}\n\n";
  1374. global << "#endif\n";
  1375. global.close();
  1376. }
  1377. // Write out the implementation.
  1378. {
  1379. string path = _outDir + string(LUA_GLOBAL_FILENAME) + string(".cpp");
  1380. ofstream global(path);
  1381. if (!global)
  1382. {
  1383. GP_ERROR("Failed to open file '%s' for generating Lua bindings.", path.c_str());
  1384. goto end;
  1385. }
  1386. global << "#include \"ScriptController.h\"\n";
  1387. global << "#include \"" << LUA_GLOBAL_FILENAME << ".h\"\n";
  1388. map<string, set<string> >::iterator iter = _includes.find(string(LUA_GLOBAL_FILENAME) + string(".h"));
  1389. if (iter != _includes.end())
  1390. {
  1391. set<string>::iterator includeIter = iter->second.begin();
  1392. for (; includeIter != iter->second.end(); includeIter++)
  1393. {
  1394. global << "#include \"" << *includeIter << "\"\n";
  1395. }
  1396. }
  1397. global << "\n";
  1398. if (bindingNS)
  1399. {
  1400. global << "namespace " << *bindingNS << "\n";
  1401. global << "{\n\n";
  1402. }
  1403. // Write out the function used to register all global bindings with Lua.
  1404. global << "void luaRegister_" << LUA_GLOBAL_FILENAME << "()\n";
  1405. global << "{\n";
  1406. global << " ScriptController* sc = ScriptController::getInstance();\n";
  1407. if (_functions.size() > 0)
  1408. {
  1409. global << "\n";
  1410. // Bind the non-member functions.
  1411. for (map<string, vector<FunctionBinding> >::iterator iter = _functions.begin(); iter != _functions.end(); iter++)
  1412. {
  1413. global << " sc->registerFunction(\"" << iter->second[0].name << "\", " << iter->second[0].getFunctionName() << ");\n";
  1414. }
  1415. }
  1416. // Generate the hierarchy map.
  1417. if (baseClasses.size() > 0)
  1418. {
  1419. global << "\n std::map<std::string, std::vector<std::string> > hierarchy;\n";
  1420. for (unsigned int i = 0, count = baseClasses.size(); i < count; i++)
  1421. {
  1422. set<string> derived;
  1423. getAllDerived(derived, baseClasses[i]);
  1424. for (set<string>::iterator iter = derived.begin(); iter != derived.end(); iter++)
  1425. {
  1426. global << " hierarchy[\"" << baseClasses[i] << "\"].push_back(\"" << *iter << "\");\n";
  1427. }
  1428. }
  1429. global << " sc->setGlobalHierarchy(hierarchy);\n";
  1430. }
  1431. // Register all enums.
  1432. if (_enums.size() > 0)
  1433. {
  1434. for (map<string, EnumBinding>::iterator iter = _enums.begin(); iter != _enums.end(); iter++)
  1435. {
  1436. global << "\n // Register enumeration " << iter->first << ".\n";
  1437. global << " {\n";
  1438. global << " std::vector<std::string> scopePath;\n";
  1439. for (unsigned int i = 0; i < iter->second.scopePath.size(); i++)
  1440. {
  1441. global << " scopePath.push_back(\"" << iter->second.scopePath[i] << "\");\n";
  1442. }
  1443. vector<string>::iterator enumIter = iter->second.values.begin();
  1444. for (; enumIter != iter->second.values.end(); enumIter++)
  1445. {
  1446. global << " sc->registerConstantString(\"" << *enumIter << "\", \"" << *enumIter << "\", scopePath);\n";
  1447. }
  1448. global << " }\n";
  1449. }
  1450. }
  1451. global << "}\n\n";
  1452. // Write out the binding functions.
  1453. for (map<string, vector<FunctionBinding> >::iterator iter = _functions.begin(); iter != _functions.end(); iter++)
  1454. {
  1455. FunctionBinding::write(global, iter->second);
  1456. }
  1457. // Write out the global enum conversion function (used to pass enums from C++ to Lua).
  1458. global << "static const char* enumStringEmpty = \"\";\n\n";
  1459. global << "const char* lua_stringFromEnumGlobal(std::string& enumname, unsigned int value)\n";
  1460. global << "{\n";
  1461. for (map<string, EnumBinding>::iterator iter = _enums.begin(); iter != _enums.end(); iter++)
  1462. {
  1463. global << " if (enumname == \"";
  1464. global << iter->first << "\")\n";
  1465. global << " return lua_stringFromEnum_" << getUniqueName(iter->first) << "((" << iter->first << ")value);\n";
  1466. }
  1467. global << "\n";
  1468. global << " GP_ERROR(\"Unrecognized enumeration type '%s'.\", enumname.c_str());\n";
  1469. global << " return enumStringEmpty;\n";
  1470. global << "}\n\n";
  1471. if (bindingNS)
  1472. global << "}\n";
  1473. global.close();
  1474. }
  1475. }
  1476. end:
  1477. luaAllCpp << "}\n\n";
  1478. if (bindingNS)
  1479. luaAllCpp << "}\n\n";
  1480. luaAllCpp.close();
  1481. if (bindingNS)
  1482. {
  1483. luaAllH << "\nnamespace " << *bindingNS << "\n";
  1484. luaAllH << "{\n\n";
  1485. }
  1486. luaAllH << "void lua_RegisterAllBindings();\n\n";
  1487. if (bindingNS)
  1488. luaAllH<< "}\n\n";
  1489. luaAllH << "#endif\n";
  1490. luaAllH.close();
  1491. SAFE_DELETE(bindingNS);
  1492. }
  1493. void Generator::getAllDerived(set<string>& derived, string classname)
  1494. {
  1495. for (unsigned int i = 0, count = _classes[classname].derived.size(); i < count; i++)
  1496. {
  1497. string derivedClassName = getIdentifier(_classes[classname].derived[i]);
  1498. derived.insert(derivedClassName);
  1499. getAllDerived(derived, derivedClassName);
  1500. }
  1501. }
  1502. void Generator::getIncludes(XMLElement* e, string filename)
  1503. {
  1504. filename.replace(filename.find(".cpp"), 4, ".h");
  1505. for (e = e->FirstChildElement("includes"); e; e = e->NextSiblingElement("includes"))
  1506. {
  1507. if (e->Attribute("refid"))
  1508. _includes[filename].insert(e->GetText());
  1509. }
  1510. }
  1511. // ----------------------------------------------------------------------------
  1512. // Utility functions
  1513. static string trim(const string& str)
  1514. {
  1515. string s = str;
  1516. while (isspace(s[0]))
  1517. {
  1518. s.erase(s.begin());
  1519. }
  1520. while (isspace(s[s.size() - 1]))
  1521. {
  1522. s.erase(s.begin() + s.size() - 1);
  1523. }
  1524. return s;
  1525. }
  1526. static string stripTypeQualifiers(const string& typeStr, FunctionBinding::Param::Kind& kind)
  1527. {
  1528. string type = typeStr;
  1529. kind = FunctionBinding::Param::KIND_VALUE;
  1530. // Check if the type is a reference.
  1531. string::size_type i = type.find("&");
  1532. if (i != type.npos)
  1533. {
  1534. kind = FunctionBinding::Param::KIND_REFERENCE;
  1535. type.erase(type.begin() + i);
  1536. }
  1537. // Check if the type is a pointer.
  1538. i = type.find("*");
  1539. if (i != type.npos)
  1540. {
  1541. kind = FunctionBinding::Param::KIND_POINTER;
  1542. type.erase(type.begin() + i);
  1543. }
  1544. // Ignore const qualifiers.
  1545. i = type.find("const ");
  1546. if (i != type.npos)
  1547. {
  1548. type.erase(type.begin() + i, type.begin() + i + 6);
  1549. }
  1550. return trim(type);
  1551. }
  1552. static inline bool isWantedFileNormal(const string& s)
  1553. {
  1554. if (s.find(".xml") == s.size() - 4)
  1555. {
  1556. if (s.find("class") == 0 || s.find("struct") == 0 ||
  1557. (s.find("_") == 0 && (s.find("h.xml") != s.npos || s.find("cpp.xml") != s.npos)))
  1558. return true;
  1559. }
  1560. return false;
  1561. }
  1562. static inline bool isNamespaceFile(const string& s)
  1563. {
  1564. if (s.find(".xml") == s.size() - 4)
  1565. {
  1566. if (s.find("namespace") == 0)
  1567. return true;
  1568. }
  1569. return false;
  1570. }
  1571. static bool getFileList(string directory, vector<string>& files, bool (*isWantedFile)(const string& s))
  1572. {
  1573. #ifdef WIN32
  1574. string path = directory + string("/*");
  1575. // Convert char to wchar.
  1576. basic_string<TCHAR> wPath;
  1577. wPath.assign(path.begin(), path.end());
  1578. WIN32_FIND_DATA FindFileData;
  1579. HANDLE hFind = FindFirstFile(wPath.c_str(), &FindFileData);
  1580. if (hFind == INVALID_HANDLE_VALUE)
  1581. {
  1582. return false;
  1583. }
  1584. do
  1585. {
  1586. // Add to the list if this is not a directory and it passes the test function.
  1587. if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
  1588. {
  1589. // Convert wchar to char.
  1590. basic_string<TCHAR> wfilename(FindFileData.cFileName);
  1591. string filename;
  1592. filename.assign(wfilename.begin(), wfilename.end());
  1593. if (isWantedFile(filename))
  1594. {
  1595. filename = string(directory) + string("/") + filename;
  1596. files.push_back(filename);
  1597. }
  1598. }
  1599. } while (FindNextFile(hFind, &FindFileData) != 0);
  1600. FindClose(hFind);
  1601. return true;
  1602. #else
  1603. string path = directory + string("/.");
  1604. struct dirent* dp;
  1605. DIR* dir = opendir(path.c_str());
  1606. if (!dir)
  1607. {
  1608. return false;
  1609. }
  1610. while ((dp = readdir(dir)) != NULL)
  1611. {
  1612. string filepath(path);
  1613. filepath.append("/");
  1614. filepath.append(dp->d_name);
  1615. struct stat buf;
  1616. if (!stat(filepath.c_str(), &buf))
  1617. {
  1618. // Add to the list if this is not a directory and it passes the test function.
  1619. if (!S_ISDIR(buf.st_mode))
  1620. {
  1621. string filename = dp->d_name;
  1622. if (isWantedFile(filename))
  1623. {
  1624. if (includePath)
  1625. filename = string(directory) + filename;
  1626. files.push_back(filename);
  1627. }
  1628. }
  1629. }
  1630. }
  1631. closedir(dir);
  1632. return true;
  1633. #endif
  1634. }
  1635. bool isReservedKeyword(string name)
  1636. {
  1637. static set<string> keywords;
  1638. if (keywords.size() == 0)
  1639. {
  1640. keywords.insert("and");
  1641. keywords.insert("break");
  1642. keywords.insert("do");
  1643. keywords.insert("else");
  1644. keywords.insert("elseif");
  1645. keywords.insert("end");
  1646. keywords.insert("false");
  1647. keywords.insert("for");
  1648. keywords.insert("function");
  1649. keywords.insert("if");
  1650. keywords.insert("in");
  1651. keywords.insert("local");
  1652. keywords.insert("nil");
  1653. keywords.insert("not");
  1654. keywords.insert("or");
  1655. keywords.insert("repeat");
  1656. keywords.insert("return");
  1657. keywords.insert("then");
  1658. keywords.insert("true");
  1659. keywords.insert("until");
  1660. keywords.insert("while");
  1661. };
  1662. return keywords.find(name) != keywords.end();
  1663. }
  1664. // ----------------------------------------------------------------------------