lua.cxx 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. /* -----------------------------------------------------------------------------
  2. * This file is part of SWIG, which is licensed as a whole under version 3
  3. * (or any later version) of the GNU General Public License. Some additional
  4. * terms also apply to certain portions of SWIG. The full details of the SWIG
  5. * license and copyrights can be found in the LICENSE and COPYRIGHT files
  6. * included with the SWIG source code as distributed by the SWIG developers
  7. * and at https://www.swig.org/legal.html.
  8. *
  9. * lua.cxx
  10. *
  11. * Lua language module for SWIG.
  12. * ----------------------------------------------------------------------------- */
  13. /* NEW LANGUAGE NOTE:
  14. * ver001
  15. this is simply a copy of tcl8.cxx, which has been renamed
  16. * ver002
  17. all non essential code commented out, program now does virtually nothing
  18. it prints to stderr the list of functions to wrap, but does not create
  19. the XXX_wrap.c file
  20. * ver003
  21. added back top(), still prints the list of fns to stderr
  22. but now creates a rather empty XXX_wrap.c with some basic boilerplate code
  23. * ver004
  24. very basic version of functionWrapper()
  25. also uncommented usage_string() to keep compiler happy
  26. this will start producing proper looking code soon (I hope)
  27. produced the wrapper code, but without any type conversion (in or out)
  28. generates a few warning because of no wrappering
  29. does not generate SWIG_init()
  30. reason for this is that lua.swg is empty
  31. we will need to add code into this to make it work
  32. * ver005/6
  33. massive rework, basing work on the pike module instead of tcl
  34. (pike module it only 1/3 of the size)(though not as complete)
  35. * ver007
  36. added simple type checking
  37. * ver008
  38. INPUT, OUTPUT, INOUT typemaps handled (though not all types yet)
  39. * ver009
  40. class support: ok for basic types, but methods still TDB
  41. (code is VERY messed up & needs to be cleaned)
  42. * ver010
  43. Added support for embedded Lua. Try swig -lua -help for more information
  44. */
  45. #include "swigmod.h"
  46. #include "cparse.h"
  47. /**** Diagnostics:
  48. With the #define REPORT(), you can change the amount of diagnostics given
  49. This helps me search the parse tree & figure out what is going on inside SWIG
  50. (because it's not clear or documented)
  51. */
  52. #define REPORT(T,D) // no info:
  53. //#define REPORT(T,D) {Printf(stdout,T"\n");} // only title
  54. //#define REPORT(T,D) {Printf(stdout,T" %p\n",n);} // title & pointer
  55. //#define REPORT(T,D) {Printf(stdout,T"\n");display_mapping(D);} // the works
  56. //#define REPORT(T,D) {Printf(stdout,T"\n");if(D)Swig_print_node(D);} // the works
  57. void display_mapping(DOH *d) {
  58. if (d == 0 || !DohIsMapping(d))
  59. return;
  60. for (Iterator it = First(d); it.item; it = Next(it)) {
  61. if (DohIsString(it.item))
  62. Printf(stdout, " %s = %s\n", it.key, it.item);
  63. else if (DohIsMapping(it.item))
  64. Printf(stdout, " %s = <mapping>\n", it.key);
  65. else if (DohIsSequence(it.item))
  66. Printf(stdout, " %s = <sequence>\n", it.key);
  67. else
  68. Printf(stdout, " %s = <unknown>\n", it.key);
  69. }
  70. }
  71. extern "C"
  72. {
  73. static int compareByLen(const DOH *f, const DOH *s) {
  74. return Len(s) - Len(f);
  75. }
  76. }
  77. /* NEW LANGUAGE NOTE:***********************************************
  78. most of the default options are handled by SWIG
  79. you can add new ones here
  80. (though for now I have not bothered)
  81. NEW LANGUAGE NOTE:END ************************************************/
  82. static const char *usage = "\
  83. Lua Options (available with -lua)\n\
  84. -elua - Generates LTR compatible wrappers for smaller devices running elua\n\
  85. -eluac - LTR compatible wrappers in \"crass compress\" mode for elua\n\
  86. -elua-emulate - Emulates behaviour of eLua. Useful only for testing.\n\
  87. Incompatible with -elua/-eluac options.\n\
  88. -nomoduleglobal - Do not register the module name as a global variable \n\
  89. but return the module table from calls to require.\n\
  90. -no-old-metatable-bindings\n\
  91. - Disable support for old-style bindings name generation, some\n\
  92. old-style members scheme etc.\n\
  93. -squash-bases - Squashes symbols from all inheritance tree of a given class\n\
  94. into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\
  95. speeds things up, but increases memory consumption.\n\
  96. \n";
  97. static int nomoduleglobal = 0;
  98. static int elua_ltr = 0;
  99. static int eluac_ltr = 0;
  100. static int elua_emulate = 0;
  101. static int squash_bases = 0;
  102. /* The new metatable bindings were introduced in SWIG 3.0.0.
  103. * old_metatable_bindings in v2:
  104. * 1. static methods will be put into the scope their respective class
  105. * belongs to as well as into the class scope itself. (only for classes without %nspace given)
  106. * 2. The layout in elua mode is somewhat different
  107. */
  108. static int old_metatable_bindings = 1;
  109. static int old_compatible_names = 1; // This flag can temporarily disable backward compatible names generation if old_metatable_bindings is enabled
  110. /* NEW LANGUAGE NOTE:***********************************************
  111. To add a new language, you need to derive your class from
  112. Language and the overload various virtual functions
  113. (more on this as I figure it out)
  114. NEW LANGUAGE NOTE:END ************************************************/
  115. class LUA:public Language {
  116. private:
  117. File *f_begin;
  118. File *f_runtime;
  119. File *f_header;
  120. File *f_wrappers;
  121. File *f_init;
  122. File *f_initbeforefunc;
  123. String *s_luacode; // luacode to be called during init
  124. String *module; //name of the module
  125. // Parameters for current class. NIL if not parsing class
  126. int have_constructor;
  127. int have_destructor;
  128. String *destructor_action;
  129. // This variable holds the name of the current class in Lua. Usually it is
  130. // the same as C++ class name, but rename directives can change it.
  131. String *proxy_class_name;
  132. // This is a so called fully qualified symname - the above proxy class name
  133. // prepended with class namespace. If class Lua name is the same as class C++ name,
  134. // then it is basically C++ fully qualified name with colons replaced with dots.
  135. String *full_proxy_class_name;
  136. // All static methods and/or variables are treated as if they were in the
  137. // special C++ namespace $(classname).SwigStatic. This is internal mechanism only
  138. // and is not visible to user in any manner. This variable holds the name
  139. // of such pseudo-namespace a.k.a the result of above expression evaluation
  140. String *class_static_nspace;
  141. // This variable holds the name of generated C function that acts as a constructor
  142. // for the currently parsed class.
  143. String *constructor_name;
  144. // Many wrappers forward calls to each other, for example staticmembervariableHandler
  145. // forwards calls to variableHandler, which, in turn, makes to call to functionWrapper.
  146. // In order to access information about whether it is a static member of class or just
  147. // a plain old variable, the current array is kept and used as a 'log' of the call stack.
  148. enum TState {
  149. NO_CPP,
  150. VARIABLE,
  151. GLOBAL_FUNC,
  152. GLOBAL_VAR,
  153. MEMBER_FUNC,
  154. CONSTRUCTOR,
  155. DESTRUCTOR,
  156. MEMBER_VAR,
  157. STATIC_FUNC,
  158. STATIC_VAR,
  159. STATIC_CONST, // enums and things like static const int x = 5;
  160. ENUM_CONST, // This is only needed for backward compatibility in C mode
  161. STATES_COUNT
  162. };
  163. bool current[STATES_COUNT];
  164. public:
  165. /* ---------------------------------------------------------------------
  166. * LUA()
  167. *
  168. * Initialize member data
  169. * --------------------------------------------------------------------- */
  170. LUA():
  171. f_begin(0),
  172. f_runtime(0),
  173. f_header(0),
  174. f_wrappers(0),
  175. f_init(0),
  176. f_initbeforefunc(0),
  177. s_luacode(0),
  178. module(0),
  179. have_constructor(0),
  180. have_destructor(0),
  181. destructor_action(0),
  182. proxy_class_name(0),
  183. full_proxy_class_name(0),
  184. class_static_nspace(0),
  185. constructor_name(0) {
  186. for (int i = 0; i < STATES_COUNT; i++)
  187. current[i] = false;
  188. }
  189. /* NEW LANGUAGE NOTE:***********************************************
  190. This is called to initialise the system & read any command line args
  191. most of this is boilerplate code, except the command line args
  192. which depends upon what args your code supports
  193. NEW LANGUAGE NOTE:END *********************************************** */
  194. /* ---------------------------------------------------------------------
  195. * main()
  196. *
  197. * Parse command line options and initializes variables.
  198. * --------------------------------------------------------------------- */
  199. virtual void main(int argc, char *argv[]) {
  200. /* Set location of SWIG library */
  201. SWIG_library_directory("lua");
  202. /* Look for certain command line options */
  203. for (int i = 1; i < argc; i++) {
  204. if (argv[i]) {
  205. if (strcmp(argv[i], "-help") == 0) { // usage flags
  206. fputs(usage, stdout);
  207. } else if (strcmp(argv[i], "-nomoduleglobal") == 0) {
  208. nomoduleglobal = 1;
  209. Swig_mark_arg(i);
  210. } else if (strcmp(argv[i], "-elua") == 0) {
  211. elua_ltr = 1;
  212. Swig_mark_arg(i);
  213. } else if (strcmp(argv[i], "-eluac") == 0) {
  214. eluac_ltr = 1;
  215. Swig_mark_arg(i);
  216. } else if (strcmp(argv[i], "-no-old-metatable-bindings") == 0) {
  217. Swig_mark_arg(i);
  218. old_metatable_bindings = 0;
  219. } else if (strcmp(argv[i], "-squash-bases") == 0) {
  220. Swig_mark_arg(i);
  221. squash_bases = 1;
  222. } else if (strcmp(argv[i], "-elua-emulate") == 0) {
  223. Swig_mark_arg(i);
  224. elua_emulate = 1;
  225. }
  226. }
  227. }
  228. if (elua_emulate && (eluac_ltr || elua_ltr )) {
  229. Printf(stderr, "Cannot have -elua-emulate with either -eluac or -elua\n");
  230. Swig_arg_error();
  231. }
  232. // Set elua_ltr if elua_emulate is requested
  233. if(elua_emulate)
  234. elua_ltr = 1;
  235. /* NEW LANGUAGE NOTE:***********************************************
  236. This is the boilerplate code, setting a few #defines
  237. and which lib directory to use
  238. the SWIG_library_directory() is also boilerplate code
  239. but it always seems to be the first line of code
  240. NEW LANGUAGE NOTE:END *********************************************** */
  241. /* Add a symbol to the parser for conditional compilation */
  242. Preprocessor_define("SWIGLUA 1", 0);
  243. /* Set language-specific configuration file */
  244. SWIG_config_file("lua.swg");
  245. /* Set typemap language */
  246. SWIG_typemap_lang("lua");
  247. /* Enable overloaded methods support */
  248. allow_overloading();
  249. }
  250. /* NEW LANGUAGE NOTE:***********************************************
  251. After calling main, SWIG parses the code to wrap (I believe)
  252. then calls top()
  253. in this is more boilerplate code to set everything up
  254. and a call to Language::top()
  255. which begins the code generations by calling the member fns
  256. after all that is more boilerplate code to close all down
  257. (overall there is virtually nothing here that needs to be edited
  258. just use as is)
  259. NEW LANGUAGE NOTE:END *********************************************** */
  260. /* ---------------------------------------------------------------------
  261. * top()
  262. * --------------------------------------------------------------------- */
  263. virtual int top(Node *n) {
  264. /* Get the module name */
  265. module = Getattr(n, "name");
  266. /* Get the output file name */
  267. String *outfile = Getattr(n, "outfile");
  268. /* Open the output file */
  269. f_begin = NewFile(outfile, "w", SWIG_output_files());
  270. if (!f_begin) {
  271. FileErrorDisplay(outfile);
  272. Exit(EXIT_FAILURE);
  273. }
  274. f_runtime = NewString("");
  275. f_init = NewString("");
  276. f_header = NewString("");
  277. f_wrappers = NewString("");
  278. f_initbeforefunc = NewString("");
  279. /* Register file targets with the SWIG file handler */
  280. Swig_register_filebyname("header", f_header);
  281. Swig_register_filebyname("wrapper", f_wrappers);
  282. Swig_register_filebyname("begin", f_begin);
  283. Swig_register_filebyname("runtime", f_runtime);
  284. Swig_register_filebyname("init", f_init);
  285. Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
  286. s_luacode = NewString("");
  287. Swig_register_filebyname("luacode", s_luacode);
  288. current[NO_CPP] = true;
  289. /* Standard stuff for the SWIG runtime section */
  290. Swig_banner(f_begin);
  291. Swig_obligatory_macros(f_runtime, "LUA");
  292. emitLuaFlavor(f_runtime);
  293. if (nomoduleglobal) {
  294. Printf(f_runtime, "#define SWIG_LUA_NO_MODULE_GLOBAL\n");
  295. } else {
  296. Printf(f_runtime, "#define SWIG_LUA_MODULE_GLOBAL\n");
  297. }
  298. if (squash_bases)
  299. Printf(f_runtime, "#define SWIG_LUA_SQUASH_BASES\n");
  300. // if (NoInclude) {
  301. // Printf(f_runtime, "#define SWIG_NOINCLUDE\n");
  302. // }
  303. Printf(f_runtime, "\n");
  304. //String *init_name = NewStringf("%(title)s_Init", module);
  305. //Printf(f_header, "#define SWIG_init %s\n", init_name);
  306. //Printf(f_header, "#define SWIG_name \"%s\"\n", module);
  307. /* SWIG_import is a special function name for importing within Lua5.1 */
  308. //Printf(f_header, "#define SWIG_import luaopen_%s\n\n", module);
  309. Printf(f_header, "#define SWIG_name \"%s\"\n", module);
  310. Printf(f_header, "#define SWIG_init luaopen_%s\n", module);
  311. Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module);
  312. Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module);
  313. Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
  314. /* %init code inclusion, effectively in the SWIG_init function */
  315. Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n");
  316. Language::top(n);
  317. Printf(f_init, "/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n");
  318. Printf(f_init, "}\n");
  319. // Done. Close up the module & write to the wrappers
  320. closeNamespaces(f_wrappers);
  321. Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n");
  322. SwigType_emit_type_table(f_runtime, f_wrappers);
  323. /* NEW LANGUAGE NOTE:***********************************************
  324. this basically combines several of the strings together
  325. and then writes it all to a file
  326. NEW LANGUAGE NOTE:END *********************************************** */
  327. Dump(f_runtime, f_begin);
  328. Dump(f_header, f_begin);
  329. Dump(f_wrappers, f_begin);
  330. Dump(f_initbeforefunc, f_begin);
  331. /* for the Lua code it needs to be properly escaped to be added into the C/C++ code */
  332. escapeCode(s_luacode);
  333. Printf(f_begin, "const char* SWIG_LUACODE=\n \"%s\";\n\n", s_luacode);
  334. Wrapper_pretty_print(f_init, f_begin);
  335. /* Close all of the files */
  336. Delete(s_luacode);
  337. Delete(f_header);
  338. Delete(f_wrappers);
  339. Delete(f_init);
  340. Delete(f_initbeforefunc);
  341. Delete(f_runtime);
  342. Delete(f_begin);
  343. /* Done */
  344. return SWIG_OK;
  345. }
  346. /* ------------------------------------------------------------
  347. * importDirective()
  348. * ------------------------------------------------------------ */
  349. virtual int importDirective(Node *n) {
  350. return Language::importDirective(n);
  351. }
  352. /* ------------------------------------------------------------
  353. * cDeclaration()
  354. * It copies sym:name to lua:name to preserve its original value
  355. * ------------------------------------------------------------ */
  356. virtual int cDeclaration(Node *n) {
  357. // class 'Language' is messing with symname in a really heavy way.
  358. // Although documentation states that sym:name is a name in
  359. // the target language space, it is not true. sym:name and
  360. // its derivatives are used in various places, including
  361. // behind-the-scene C code generation. The best way is not to
  362. // touch it at all.
  363. // But we need to know what was the name of function/variable
  364. // etc that user desired, that's why we store correct symname
  365. // as lua:name
  366. String *symname = Getattr(n, "sym:name");
  367. if (symname)
  368. Setattr(n, "lua:name", symname);
  369. return Language::cDeclaration(n);
  370. }
  371. virtual int constructorDeclaration(Node *n) {
  372. Setattr(n, "lua:name", Getattr(n, "sym:name"));
  373. return Language::constructorDeclaration(n);
  374. }
  375. virtual int destructorDeclaration(Node *n) {
  376. Setattr(n, "lua:name", Getattr(n, "sym:name"));
  377. return Language::destructorDeclaration(n);
  378. }
  379. /* NEW LANGUAGE NOTE:***********************************************
  380. This is it!
  381. you get this one right, and most of your work is done
  382. but it's going to take some file to get it working right
  383. quite a bit of this is generally boilerplate code
  384. (or stuff I don't understand)
  385. that which matters will have extra added comments
  386. NEW LANGUAGE NOTE:END *********************************************** */
  387. /* ---------------------------------------------------------------------
  388. * functionWrapper()
  389. *
  390. * Create a function declaration and register it with the interpreter.
  391. * --------------------------------------------------------------------- */
  392. /* -----------------------------------------------------------------------
  393. * registerMethod()
  394. *
  395. * Determines wrap name of a method, its scope etc and calls
  396. * registerMethod overload with correct arguments
  397. * Overloaded variant adds method to the "methods" array of specified lua scope/class
  398. * ---------------------------------------------------------------------- */
  399. void registerMethod(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) {
  400. String *symname = Getattr(n, "sym:name");
  401. assert(symname);
  402. if (Getattr(n, "sym:nextSibling"))
  403. return;
  404. // Lua scope. It is not symbol NSpace, it is the actual key to retrieve getCArraysHash.
  405. String *luaScope = luaCurrentSymbolNSpace();
  406. if (overwrite)
  407. luaScope = overwriteLuaScope;
  408. String *wrapname = 0;
  409. String *mrename;
  410. if (current[NO_CPP] || !getCurrentClass()) {
  411. mrename = symname;
  412. } else {
  413. assert(!current[NO_CPP]);
  414. if (current[STATIC_FUNC] || current[MEMBER_FUNC]) {
  415. mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname);
  416. } else {
  417. mrename = symname;
  418. }
  419. }
  420. wrapname = Swig_name_wrapper(mrename);
  421. registerMethod(n, wrapname, luaScope);
  422. }
  423. /* -----------------------------------------------------------------------
  424. * registerMethod()
  425. *
  426. * Add method to the "methods" C array of given namespace/class
  427. * ---------------------------------------------------------------------- */
  428. void registerMethod(Node *n, String* wname, String *luaScope) {
  429. assert(n);
  430. Hash *nspaceHash = getCArraysHash(luaScope);
  431. String *s_ns_methods_tab = Getattr(nspaceHash, "methods");
  432. String *lua_name = Getattr(n, "lua:name");
  433. if (elua_ltr || eluac_ltr)
  434. Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL);
  435. else
  436. Printv(s_ns_methods_tab, tab4, "{ \"", lua_name, "\", ", wname, "},\n", NIL);
  437. // Add to the metatable if method starts with '__'
  438. const char * tn = Char(lua_name);
  439. if (tn[0]=='_' && tn[1] == '_' && !eluac_ltr) {
  440. String *metatable_tab = Getattr(nspaceHash, "metatable");
  441. assert(metatable_tab);
  442. if (elua_ltr)
  443. Printv(metatable_tab, tab4, "{LSTRKEY(\"", lua_name, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL);
  444. else
  445. Printv(metatable_tab, tab4, "{ \"", lua_name, "\", ", wname, "},\n", NIL);
  446. }
  447. }
  448. virtual int functionWrapper(Node *n) {
  449. REPORT("functionWrapper", n);
  450. String *name = Getattr(n, "name");
  451. String *iname = Getattr(n, "sym:name");
  452. String *lua_name = Getattr(n, "lua:name");
  453. assert(lua_name);
  454. SwigType *d = Getattr(n, "type");
  455. ParmList *l = Getattr(n, "parms");
  456. Parm *p;
  457. String *tm;
  458. int i;
  459. //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current);
  460. String *overname = 0;
  461. if (Getattr(n, "sym:overloaded")) {
  462. overname = Getattr(n, "sym:overname");
  463. } else {
  464. if (!luaAddSymbol(lua_name, n)) {
  465. return SWIG_ERROR;
  466. }
  467. }
  468. /* NEW LANGUAGE NOTE:***********************************************
  469. the wrapper object holds all the wrapper code
  470. we need to add a couple of local variables
  471. NEW LANGUAGE NOTE:END *********************************************** */
  472. Wrapper *f = NewWrapper();
  473. Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0");
  474. String *wname = Swig_name_wrapper(iname);
  475. if (overname) {
  476. Append(wname, overname);
  477. }
  478. if (current[CONSTRUCTOR]) {
  479. if (constructor_name != 0)
  480. Delete(constructor_name);
  481. constructor_name = Copy(wname);
  482. }
  483. /* NEW LANGUAGE NOTE:***********************************************
  484. the format of a lua fn is:
  485. static int wrap_XXX(lua_State* L){...}
  486. this line adds this into the wrapper code
  487. NEW LANGUAGE NOTE:END *********************************************** */
  488. Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
  489. // SWIG_fail in lua leads to a call to lua_error() which calls longjmp()
  490. // which means the destructors of any live function-local C++ objects won't
  491. // get run. To avoid this happening, we wrap almost everything in the
  492. // function in a block, and end that right before lua_error() at which
  493. // point those destructors will get called.
  494. if (CPlusPlus) Append(f->def, "\n{");
  495. /* NEW LANGUAGE NOTE:***********************************************
  496. this prints the list of args, eg for a C fn
  497. int gcd(int x,int y);
  498. it will print
  499. int arg1;
  500. int arg2;
  501. NEW LANGUAGE NOTE:END *********************************************** */
  502. /* Write code to extract function parameters. */
  503. emit_parameter_variables(l, f);
  504. /* Attach the standard typemaps */
  505. emit_attach_parmmaps(l, f);
  506. Setattr(n, "wrap:parms", l);
  507. /* Get number of required and total arguments */
  508. int num_arguments = emit_num_arguments(l);
  509. int num_required = emit_num_required(l);
  510. int varargs = emit_isvarargs(l);
  511. // Check if we have to ignore arguments that are passed by LUA.
  512. // Needed for unary minus, where lua passes two arguments and
  513. // we have to ignore the second.
  514. int args_to_ignore = 0;
  515. if (Getattr(n, "lua:ignore_args")) {
  516. args_to_ignore = GetInt(n, "lua:ignore_args");
  517. }
  518. /* NEW LANGUAGE NOTE:***********************************************
  519. from here on in, it gets rather hairy
  520. this is the code to convert from the scripting language to C/C++
  521. some of the stuff will refer to the typemaps code written in your swig file
  522. (lua.swg), and some is done in the code here
  523. I suppose you could do all the conversion in C, but it would be a nightmare to do
  524. NEW LANGUAGE NOTE:END *********************************************** */
  525. /* Generate code for argument marshalling */
  526. // String *description = NewString("");
  527. /* NEW LANGUAGE NOTE:***********************************************
  528. argument_check is a new feature I added to check types of arguments:
  529. eg for int gcd(int,int)
  530. I want to check that arg1 & arg2 really are integers
  531. NEW LANGUAGE NOTE:END *********************************************** */
  532. String *argument_check = NewString("");
  533. String *argument_parse = NewString("");
  534. String *checkfn = NULL;
  535. char source[64];
  536. Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n", Swig_name_str(n), num_required + args_to_ignore, num_arguments + args_to_ignore);
  537. for (i = 0, p = l; i < num_arguments; i++) {
  538. while (checkAttribute(p, "tmap:in:numinputs", "0")) {
  539. p = Getattr(p, "tmap:in:next");
  540. }
  541. SwigType *pt = Getattr(p, "type");
  542. /* Look for an input typemap */
  543. sprintf(source, "%d", i + 1);
  544. if ((tm = Getattr(p, "tmap:in"))) {
  545. Replaceall(tm, "$input", source);
  546. Setattr(p, "emit:input", source);
  547. if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
  548. Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
  549. } else {
  550. Replaceall(tm, "$disown", "0");
  551. }
  552. /* NEW LANGUAGE NOTE:***********************************************
  553. look for a 'checkfn' typemap
  554. this an additional parameter added to the in typemap
  555. if found the type will be tested for
  556. this will result in code either in the
  557. argument_check or argument_parse string
  558. NEW LANGUAGE NOTE:END *********************************************** */
  559. if ((checkfn = Getattr(p, "tmap:in:checkfn"))) {
  560. if (i < num_required) {
  561. Printf(argument_check, "if(!%s(L,%s))", checkfn, source);
  562. } else {
  563. Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source);
  564. }
  565. Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", Swig_name_str(n), source, SwigType_str(pt, 0));
  566. }
  567. /* NEW LANGUAGE NOTE:***********************************************
  568. lua states the number of arguments passed to a function using the fn
  569. lua_gettop()
  570. we can use this to deal with default arguments
  571. NEW LANGUAGE NOTE:END *********************************************** */
  572. if (i < num_required) {
  573. Printf(argument_parse, "%s\n", tm);
  574. } else {
  575. Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm);
  576. }
  577. p = Getattr(p, "tmap:in:next");
  578. continue;
  579. } else {
  580. /* NEW LANGUAGE NOTE:***********************************************
  581. // why is this code not called when I don't have a typemap?
  582. // instead of giving a warning, no code is generated
  583. NEW LANGUAGE NOTE:END *********************************************** */
  584. Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
  585. break;
  586. }
  587. }
  588. // add all argcheck code
  589. Printv(f->code, argument_check, argument_parse, NIL);
  590. /* Check for trailing varargs */
  591. if (varargs) {
  592. if (p && (tm = Getattr(p, "tmap:in"))) {
  593. Replaceall(tm, "$input", "varargs");
  594. Printv(f->code, tm, "\n", NIL);
  595. }
  596. }
  597. /* Insert constraint checking code */
  598. for (p = l; p;) {
  599. if ((tm = Getattr(p, "tmap:check"))) {
  600. Printv(f->code, tm, "\n", NIL);
  601. p = Getattr(p, "tmap:check:next");
  602. } else {
  603. p = nextSibling(p);
  604. }
  605. }
  606. /* Insert cleanup code */
  607. String *cleanup = NewString("");
  608. for (p = l; p;) {
  609. if ((tm = Getattr(p, "tmap:freearg"))) {
  610. Printv(cleanup, tm, "\n", NIL);
  611. p = Getattr(p, "tmap:freearg:next");
  612. } else {
  613. p = nextSibling(p);
  614. }
  615. }
  616. /* Insert argument output code */
  617. String *outarg = NewString("");
  618. for (p = l; p;) {
  619. if ((tm = Getattr(p, "tmap:argout"))) {
  620. // // managing the number of returning variables
  621. // if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){
  622. // int i=GetInt(p,"tmap:argout:numoutputs");
  623. // printf("got argout:numoutputs of %d\n",i);
  624. // returnval+=GetInt(p,"tmap:argout:numoutputs");
  625. // }
  626. // else returnval++;
  627. Replaceall(tm, "$arg", Getattr(p, "emit:input"));
  628. Replaceall(tm, "$input", Getattr(p, "emit:input"));
  629. Printv(outarg, tm, "\n", NIL);
  630. p = Getattr(p, "tmap:argout:next");
  631. } else {
  632. p = nextSibling(p);
  633. }
  634. }
  635. // Remember C name of the wrapping function
  636. Setattr(n, "wrap:name", wname);
  637. /* Emit the function call */
  638. String *actioncode = emit_action(n);
  639. /* NEW LANGUAGE NOTE:***********************************************
  640. FIXME:
  641. returns 1 if there is a void return type
  642. this is because there is a typemap for void
  643. NEW LANGUAGE NOTE:END *********************************************** */
  644. // Return value if necessary
  645. if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) {
  646. // managing the number of returning variables
  647. // if (numoutputs=Getattr(tm,"numoutputs")){
  648. // int i=GetInt(tm,"numoutputs");
  649. // printf("return numoutputs %d\n",i);
  650. // returnval+=GetInt(tm,"numoutputs");
  651. // }
  652. // else returnval++;
  653. if (GetFlag(n, "feature:new")) {
  654. Replaceall(tm, "$owner", "1");
  655. } else {
  656. Replaceall(tm, "$owner", "0");
  657. }
  658. Printf(f->code, "%s\n", tm);
  659. // returnval++;
  660. } else {
  661. Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
  662. }
  663. emit_return_variable(n, d, f);
  664. /* Output argument output code */
  665. Printv(f->code, outarg, NIL);
  666. /* Output cleanup code */
  667. Printv(f->code, cleanup, NIL);
  668. /* Look to see if there is any newfree cleanup code */
  669. if (GetFlag(n, "feature:new")) {
  670. if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) {
  671. Printf(f->code, "%s\n", tm);
  672. }
  673. }
  674. /* See if there is any return cleanup code */
  675. if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) {
  676. Printf(f->code, "%s\n", tm);
  677. }
  678. /* Close the function */
  679. Printv(f->code, "return SWIG_arg;\n", NIL);
  680. // add the failure cleanup code:
  681. Printv(f->code, "\nfail: SWIGUNUSED;\n", "$cleanup", NIL);
  682. if (CPlusPlus) Append(f->code, "}\n");
  683. Printv(f->code, "lua_error(L);\n", NIL);
  684. // lua_error() calls longjmp() but we need a dummy return to avoid compiler
  685. // warnings.
  686. Printv(f->code, "return 0;\n", NIL);
  687. Printf(f->code, "}\n");
  688. /* Substitute the cleanup code */
  689. Replaceall(f->code, "$cleanup", cleanup);
  690. /* Substitute the function name */
  691. Replaceall(f->code, "$symname", iname);
  692. Replaceall(f->code, "$result", Swig_cresult_name());
  693. /* Dump the function out */
  694. /* in Lua we will not emit the destructor as a wrapper function,
  695. Lua will automatically call the destructor when the object is free'd
  696. However: you cannot just skip this function as it will not emit
  697. any custom destructor (using %extend), as you need to call emit_action()
  698. Therefore we go though the whole function,
  699. but do not write the code into the wrapper
  700. */
  701. if (!current[DESTRUCTOR]) {
  702. Wrapper_print(f, f_wrappers);
  703. }
  704. /* NEW LANGUAGE NOTE:***********************************************
  705. register the function in SWIG
  706. different language mappings seem to use different ideas
  707. NEW LANGUAGE NOTE:END *********************************************** */
  708. /* Now register the function with the interpreter. */
  709. int result = SWIG_OK;
  710. if (Getattr(n, "sym:overloaded")) {
  711. if (!Getattr(n, "sym:nextSibling")) {
  712. result = dispatchFunction(n);
  713. }
  714. }
  715. Delete(argument_check);
  716. Delete(argument_parse);
  717. Delete(cleanup);
  718. Delete(outarg);
  719. // Delete(description);
  720. DelWrapper(f);
  721. return result;
  722. }
  723. /* ------------------------------------------------------------
  724. * dispatchFunction()
  725. *
  726. * Emit overloading dispatch function
  727. * ------------------------------------------------------------ */
  728. /* NEW LANGUAGE NOTE:***********************************************
  729. This is an extra function used for overloading of functions
  730. it checks the args & then calls the relevant fn
  731. most of the real work in again typemaps:
  732. look for %typecheck(SWIG_TYPECHECK_*) in the .swg file
  733. NEW LANGUAGE NOTE:END *********************************************** */
  734. int dispatchFunction(Node *n) {
  735. //REPORT("dispatchFunction", n);
  736. /* Last node in overloaded chain */
  737. int maxargs;
  738. String *tmp = NewString("");
  739. String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs);
  740. /* Generate a dispatch wrapper for all overloaded functions */
  741. Wrapper *f = NewWrapper();
  742. String *symname = Getattr(n, "sym:name");
  743. String *lua_name = Getattr(n, "lua:name");
  744. assert(lua_name);
  745. String *wname = Swig_name_wrapper(symname);
  746. //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs);
  747. if (!luaAddSymbol(lua_name, n)) {
  748. DelWrapper(f);
  749. Delete(dispatch);
  750. Delete(tmp);
  751. return SWIG_ERROR;
  752. }
  753. Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
  754. Wrapper_add_local(f, "argc", "int argc");
  755. Printf(tmp, "int argv[%d]={1", maxargs + 1);
  756. for (int i = 1; i <= maxargs; i++) {
  757. Printf(tmp, ",%d", i + 1);
  758. }
  759. Printf(tmp, "}");
  760. Wrapper_add_local(f, "argv", tmp);
  761. Printf(f->code, "argc = lua_gettop(L);\n");
  762. Replaceall(dispatch, "$args", "self,args");
  763. Printv(f->code, dispatch, "\n", NIL);
  764. Node *sibl = n;
  765. while (Getattr(sibl, "sym:previousSibling"))
  766. sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up
  767. String *protoTypes = NewString("");
  768. do {
  769. String *fulldecl = Swig_name_decl(sibl);
  770. Printf(protoTypes, "\n\" %s\\n\"", fulldecl);
  771. Delete(fulldecl);
  772. } while ((sibl = Getattr(sibl, "sym:nextSibling")));
  773. Printf(f->code, "SWIG_Lua_pusherrstring(L,\"Wrong arguments for overloaded function '%s'\\n\"\n"
  774. "\" Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes);
  775. Delete(protoTypes);
  776. Printf(f->code, "lua_error(L);return 0;\n");
  777. Printv(f->code, "}\n", NIL);
  778. Wrapper_print(f, f_wrappers);
  779. // Remember C name of the wrapping function
  780. Setattr(n, "wrap:name", wname);
  781. if (current[CONSTRUCTOR]) {
  782. if (constructor_name != 0)
  783. Delete(constructor_name);
  784. constructor_name = Copy(wname);
  785. }
  786. DelWrapper(f);
  787. Delete(dispatch);
  788. Delete(tmp);
  789. return SWIG_OK;
  790. }
  791. /* ------------------------------------------------------------
  792. * Add variable to "attributes" C arrays of given namespace or class.
  793. * Input is node. Based on the state of "current" array it determines
  794. * the name of the getter function, setter function etc and calls
  795. * registerVariable overload with necessary params.
  796. * Lua scope could be overwritten. (Used only for backward compatibility)
  797. * ------------------------------------------------------------ */
  798. void registerVariable(Node *n, bool overwrite = false, String *overwriteLuaScope = 0) {
  799. int assignable = is_assignable(n);
  800. String *symname = Getattr(n, "sym:name");
  801. assert(symname);
  802. // Lua scope. It is not symbol NSpace, it is the actual key to retrieve getCArraysHash.
  803. String *luaScope = luaCurrentSymbolNSpace();
  804. if (overwrite)
  805. luaScope = overwriteLuaScope;
  806. // Getter and setter
  807. String *getName = 0;
  808. String *setName = 0;
  809. String *mrename = 0;
  810. if (current[NO_CPP] || !getCurrentClass()) {
  811. // Global variable
  812. getName = Swig_name_get(getNSpace(), symname);
  813. if (assignable)
  814. setName = Swig_name_set(getNSpace(), symname);
  815. } else {
  816. assert(!current[NO_CPP]);
  817. if (current[STATIC_VAR] ) {
  818. mrename = Swig_name_member(getNSpace(), getClassPrefix(), symname);
  819. getName = Swig_name_get(0, mrename);
  820. if (assignable)
  821. setName = Swig_name_set(0, mrename);
  822. } else if (current[MEMBER_VAR]) {
  823. mrename = Swig_name_member(0, getClassPrefix(), symname);
  824. getName = Swig_name_get(getNSpace(), mrename);
  825. if (assignable)
  826. setName = Swig_name_set(getNSpace(), mrename);
  827. } else {
  828. assert(false);
  829. }
  830. }
  831. getName = Swig_name_wrapper(getName);
  832. if (setName)
  833. setName = Swig_name_wrapper(setName);
  834. registerVariable(luaScope, n, getName, setName);
  835. }
  836. /* ------------------------------------------------------------
  837. * registerVariable()
  838. *
  839. * Add variable to the "attributes" (or "get"/"set" in
  840. * case of elua_ltr) C arrays of given namespace or class
  841. * ------------------------------------------------------------ */
  842. void registerVariable(String *lua_nspace_or_class_name, Node *n, String *getName, String *setName) {
  843. String *unassignable = NewString("SWIG_Lua_set_immutable");
  844. if (setName == 0 || GetFlag(n, "feature:immutable")) {
  845. setName = unassignable;
  846. }
  847. Hash *nspaceHash = getCArraysHash(lua_nspace_or_class_name);
  848. String *s_ns_methods_tab = Getattr(nspaceHash, "methods");
  849. String *s_ns_var_tab = Getattr(nspaceHash, "attributes");
  850. String *lua_name = Getattr(n, "lua:name");
  851. if (elua_ltr) {
  852. String *s_ns_dot_get = Getattr(nspaceHash, "get");
  853. String *s_ns_dot_set = Getattr(nspaceHash, "set");
  854. Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, lua_name, getName);
  855. Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, lua_name, setName);
  856. } else if (eluac_ltr) {
  857. Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL);
  858. Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", lua_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL);
  859. } else {
  860. Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, lua_name, getName, setName);
  861. }
  862. }
  863. /* ------------------------------------------------------------
  864. * variableWrapper()
  865. * ------------------------------------------------------------ */
  866. virtual int variableWrapper(Node *n) {
  867. /* NEW LANGUAGE NOTE:***********************************************
  868. Language::variableWrapper(n) will generate two wrapper fns
  869. Foo_get & Foo_set by calling functionWrapper()
  870. so we will just add these into the variable lists
  871. ideally we should not have registered these as functions,
  872. only WRT this variable will look into this later.
  873. NEW LANGUAGE NOTE:END *********************************************** */
  874. // REPORT("variableWrapper", n);
  875. String *lua_name = Getattr(n, "lua:name");
  876. assert(lua_name);
  877. (void)lua_name;
  878. current[VARIABLE] = true;
  879. // let SWIG generate the wrappers
  880. int result = Language::variableWrapper(n);
  881. // It is impossible to use registerVariable, because sym:name of the Node is currently
  882. // in an undefined state - the callees of this function may have modified it.
  883. // registerVariable should be used from respective callees.*
  884. current[VARIABLE] = false;
  885. return result;
  886. }
  887. /* ------------------------------------------------------------
  888. * Add constant to appropriate C array. constantRecord is an array record.
  889. * Actually, in current implementation it is resolved consttab typemap
  890. * ------------------------------------------------------------ */
  891. void registerConstant(String *nspace, String *constantRecord) {
  892. Hash *nspaceHash = getCArraysHash(nspace);
  893. String *s_const_tab = 0;
  894. if (eluac_ltr || elua_ltr)
  895. // In elua everything goes to "methods" tab
  896. s_const_tab = Getattr(nspaceHash, "methods");
  897. else
  898. s_const_tab = Getattr(nspaceHash, "constants");
  899. assert(s_const_tab);
  900. Printf(s_const_tab, " %s,\n", constantRecord);
  901. if ((eluac_ltr || elua_ltr) && old_metatable_bindings) {
  902. s_const_tab = Getattr(nspaceHash, "constants");
  903. assert(s_const_tab);
  904. Printf(s_const_tab, " %s,\n", constantRecord);
  905. }
  906. }
  907. /* ------------------------------------------------------------
  908. * constantWrapper()
  909. * ------------------------------------------------------------ */
  910. virtual int constantWrapper(Node *n) {
  911. REPORT("constantWrapper", n);
  912. String *name = Getattr(n, "name");
  913. String *iname = Getattr(n, "sym:name");
  914. String *lua_name = Getattr(n, "lua:name");
  915. if (lua_name == 0)
  916. lua_name = iname;
  917. String *nsname = Copy(iname);
  918. SwigType *type = Getattr(n, "type");
  919. String *rawval = Getattr(n, "rawval");
  920. String *value = rawval ? rawval : Getattr(n, "value");
  921. String *tm;
  922. String *lua_name_v2 = 0;
  923. String *tm_v2 = 0;
  924. String *iname_v2 = 0;
  925. Node *n_v2 = 0;
  926. if (!luaAddSymbol(lua_name, n))
  927. return SWIG_ERROR;
  928. Swig_save("lua_constantMember", n, "sym:name", NIL);
  929. Setattr(n, "sym:name", lua_name);
  930. /* Special hook for member pointer */
  931. if (SwigType_type(type) == T_MPOINTER) {
  932. String *wname = Swig_name_wrapper(iname);
  933. Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value);
  934. value = Char(wname);
  935. }
  936. if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
  937. Replaceall(tm, "$value", value);
  938. Replaceall(tm, "$nsname", nsname);
  939. registerConstant(luaCurrentSymbolNSpace(), tm);
  940. } else if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
  941. Replaceall(tm, "$value", value);
  942. Replaceall(tm, "$nsname", nsname);
  943. Printf(f_init, "%s\n", tm);
  944. } else {
  945. Delete(nsname);
  946. nsname = 0;
  947. Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
  948. Swig_restore(n);
  949. return SWIG_NOWRAP;
  950. }
  951. bool make_v2_compatible = old_metatable_bindings && getCurrentClass() && old_compatible_names;
  952. if (make_v2_compatible) {
  953. // Don't do anything for enums in C mode - they are already
  954. // wrapped correctly
  955. if (CPlusPlus || !current[ENUM_CONST]) {
  956. lua_name_v2 = Swig_name_member(0, proxy_class_name, lua_name);
  957. iname_v2 = Swig_name_member(0, proxy_class_name, iname);
  958. n_v2 = Copy(n);
  959. if (!luaAddSymbol(iname_v2, n, getNSpace())) {
  960. Swig_restore(n);
  961. return SWIG_ERROR;
  962. }
  963. Setattr(n_v2, "sym:name", lua_name_v2);
  964. tm_v2 = Swig_typemap_lookup("consttab", n_v2, name, 0);
  965. if (tm_v2) {
  966. Replaceall(tm_v2, "$value", value);
  967. Replaceall(tm_v2, "$nsname", nsname);
  968. registerConstant(getNSpace(), tm_v2);
  969. } else {
  970. tm_v2 = Swig_typemap_lookup("constcode", n_v2, name, 0);
  971. if (!tm_v2) {
  972. // This can't be.
  973. assert(false);
  974. Swig_restore(n);
  975. return SWIG_ERROR;
  976. }
  977. Replaceall(tm_v2, "$value", value);
  978. Replaceall(tm_v2, "$nsname", nsname);
  979. Printf(f_init, "%s\n", tm_v2);
  980. }
  981. Delete(n_v2);
  982. }
  983. }
  984. Swig_restore(n);
  985. Delete(nsname);
  986. return SWIG_OK;
  987. }
  988. /* ------------------------------------------------------------
  989. * nativeWrapper()
  990. * ------------------------------------------------------------ */
  991. virtual int nativeWrapper(Node *n) {
  992. // REPORT("nativeWrapper", n);
  993. String *symname = Getattr(n, "sym:name");
  994. String *wrapname = Getattr(n, "wrap:name");
  995. if (!luaAddSymbol(wrapname, n))
  996. return SWIG_ERROR;
  997. Hash *nspaceHash = getCArraysHash(getNSpace());
  998. String *s_ns_methods_tab = Getattr(nspaceHash, "methods");
  999. Printv(s_ns_methods_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL);
  1000. // return Language::nativeWrapper(n); // this does nothing...
  1001. return SWIG_OK;
  1002. }
  1003. /* ------------------------------------------------------------
  1004. * enumDeclaration()
  1005. * ------------------------------------------------------------ */
  1006. virtual int enumDeclaration(Node *n) {
  1007. if (getCurrentClass() && (cplus_mode != PUBLIC))
  1008. return SWIG_NOWRAP;
  1009. current[STATIC_CONST] = true;
  1010. current[ENUM_CONST] = true;
  1011. // There is some slightly specific behaviour with enums. Basically,
  1012. // their NSpace may be tracked separately. The code below tries to work around
  1013. // this issue to some degree.
  1014. // The idea is the same as in classHandler - to drop old names generation if
  1015. // enum is in class in namespace.
  1016. const int old_compatible_names_saved = old_compatible_names;
  1017. if (getNSpace() || ( Getattr(n, "sym:nspace") != 0 && Len(Getattr(n, "sym:nspace")) > 0 ) ) {
  1018. old_compatible_names = 0;
  1019. }
  1020. int result = Language::enumDeclaration(n);
  1021. current[STATIC_CONST] = false;
  1022. current[ENUM_CONST] = false;
  1023. old_compatible_names = old_compatible_names_saved;
  1024. return result;
  1025. }
  1026. /* ------------------------------------------------------------
  1027. * enumvalueDeclaration()
  1028. * ------------------------------------------------------------ */
  1029. virtual int enumvalueDeclaration(Node *n) {
  1030. if (getCurrentClass() && (cplus_mode != PUBLIC))
  1031. return SWIG_NOWRAP;
  1032. Swig_require("enumvalueDeclaration", n, "*name", "?value", "*sym:name", NIL);
  1033. String *symname = Getattr(n, "sym:name");
  1034. String *value = Getattr(n, "value");
  1035. String *name = Getattr(n, "name");
  1036. String *tmpValue;
  1037. Node *parent = parentNode(n);
  1038. if (value)
  1039. tmpValue = NewString(value);
  1040. else
  1041. tmpValue = NewString(name);
  1042. Setattr(n, "value", tmpValue);
  1043. Setattr(n, "name", tmpValue); /* for wrapping of enums in a namespace when emit_action is used */
  1044. if (GetFlag(parent, "scopedenum")) {
  1045. symname = Swig_name_member(0, Getattr(parent, "sym:name"), symname);
  1046. Setattr(n, "sym:name", symname);
  1047. Delete(symname);
  1048. }
  1049. int result = constantWrapper(n);
  1050. Delete(tmpValue);
  1051. Swig_restore(n);
  1052. return result;
  1053. }
  1054. /* ------------------------------------------------------------
  1055. * classDeclaration()
  1056. * ------------------------------------------------------------ */
  1057. virtual int classDeclaration(Node *n) {
  1058. return Language::classDeclaration(n);
  1059. }
  1060. /* ------------------------------------------------------------
  1061. * Helper function that adds record to appropriate C arrays
  1062. * ------------------------------------------------------------ */
  1063. void registerClass(String *scope, String *wrap_class) {
  1064. assert(wrap_class);
  1065. Hash *nspaceHash = getCArraysHash(scope);
  1066. String *ns_classes = Getattr(nspaceHash, "classes");
  1067. Printv(ns_classes, "&", wrap_class, ",\n", NIL);
  1068. if (elua_ltr || eluac_ltr) {
  1069. String *ns_methods = Getattr(nspaceHash, "methods");
  1070. Hash *class_hash = getCArraysHash(class_static_nspace);
  1071. assert(class_hash);
  1072. String *cls_methods = Getattr(class_hash, "methods:name");
  1073. assert(cls_methods);
  1074. Printv(ns_methods, tab4, "{LSTRKEY(\"", proxy_class_name, "\")", ", LROVAL(", cls_methods, ")", "},\n", NIL);
  1075. }
  1076. }
  1077. /* ------------------------------------------------------------
  1078. * classHandler()
  1079. * ------------------------------------------------------------ */
  1080. virtual int classHandler(Node *n) {
  1081. //REPORT("classHandler", n);
  1082. String *mangled_full_proxy_class_name = 0;
  1083. String *destructor_name = 0;
  1084. String *nspace = getNSpace();
  1085. constructor_name = 0;
  1086. have_constructor = 0;
  1087. have_destructor = 0;
  1088. destructor_action = 0;
  1089. assert(class_static_nspace == 0);
  1090. assert(full_proxy_class_name == 0);
  1091. assert(proxy_class_name == 0);
  1092. current[NO_CPP] = false;
  1093. proxy_class_name = Getattr(n, "sym:name");
  1094. // We have to enforce nspace here, because technically we are already
  1095. // inside class parsing (getCurrentClass != 0), but we should register
  1096. // class in its parent namespace
  1097. if (!luaAddSymbol(proxy_class_name, n, nspace))
  1098. return SWIG_ERROR;
  1099. if (nspace == 0)
  1100. full_proxy_class_name = NewStringf("%s", proxy_class_name);
  1101. else
  1102. full_proxy_class_name = NewStringf("%s.%s", nspace, proxy_class_name);
  1103. assert(full_proxy_class_name);
  1104. mangled_full_proxy_class_name = Swig_name_mangle(full_proxy_class_name);
  1105. SwigType *t = Copy(Getattr(n, "name"));
  1106. SwigType *fr_t = SwigType_typedef_resolve_all(t); /* Create fully resolved type */
  1107. SwigType *t_tmp = 0;
  1108. t_tmp = SwigType_typedef_qualified(fr_t); // Temporal variable
  1109. Delete(fr_t);
  1110. fr_t = SwigType_strip_qualifiers(t_tmp);
  1111. String *mangled_fr_t = 0;
  1112. mangled_fr_t = SwigType_manglestr(fr_t);
  1113. // not sure exactly how this works,
  1114. // but tcl has a static hashtable of all classes emitted and then only emits code for them once.
  1115. // this fixes issues in test suites: template_default2 & template_specialization
  1116. // * if i understand correctly, this is a bug.
  1117. // * consider effect on template_specialization_defarg
  1118. static Hash *emitted = NewHash();
  1119. if (GetFlag(emitted, mangled_fr_t)) {
  1120. full_proxy_class_name = 0;
  1121. proxy_class_name = 0;
  1122. return SWIG_NOWRAP;
  1123. }
  1124. SetFlag(emitted, mangled_fr_t);
  1125. // We treat class T as both 'class' and 'namespace'. All static members, attributes
  1126. // and constants are considered part of namespace T, all members - part of the 'class'
  1127. // Now, here is a trick. Static methods, attributes and non-static methods and attributes
  1128. // are described with same structures - swig_lua_attribute/swig_lua_method. Instead of calling
  1129. // getCArraysHash(class name) to initialize things for static methods/attributes and then
  1130. // manually doing same initialization for non-static methods, we call getCArraysHash 2 times:
  1131. // 1) With name "class name" + "." + "SwigStatic" to initialize static things
  1132. // 2) With "class name" to initialize non-static things
  1133. Hash *instance_cls = getCArraysHash(full_proxy_class_name, false);
  1134. assert(instance_cls);
  1135. String *s_attr_tab_name = Getattr(instance_cls, "attributes:name");
  1136. String *s_methods_tab_name = Getattr(instance_cls, "methods:name");
  1137. SetFlag(instance_cls, "lua:no_namespaces");
  1138. SetFlag(instance_cls, "lua:no_classes");
  1139. SetFlag(instance_cls, "lua:class_instance");
  1140. /* There is no use for "constants", "classes" and "namespaces" arrays.
  1141. * All constants are considered part of static part of class.
  1142. */
  1143. class_static_nspace = NewStringf("%s%sSwigStatic", full_proxy_class_name, NSPACE_SEPARATOR);
  1144. Hash *static_cls = getCArraysHash(class_static_nspace, false);
  1145. assert(static_cls);
  1146. SetFlag(static_cls, "lua:no_namespaces");
  1147. SetFlag(static_cls, "lua:class_static");
  1148. // Notifying instance_cls and static_cls hashes about each other
  1149. Setattr(instance_cls, "lua:class_instance:static_hash", static_cls);
  1150. Setattr(static_cls, "lua:class_static:instance_hash", instance_cls);
  1151. const int old_compatible_names_saved = old_compatible_names;
  1152. // If class has %nspace enabled, then generation of backward compatible names
  1153. // should be disabled
  1154. if (getNSpace()) {
  1155. old_compatible_names = 0;
  1156. }
  1157. /* There is no use for "classes" and "namespaces" arrays. Subclasses are not supported
  1158. * by SWIG and namespaces couldn't be nested inside classes (C++ Standard)
  1159. */
  1160. // Generate normal wrappers
  1161. Language::classHandler(n);
  1162. old_compatible_names = old_compatible_names_saved;
  1163. SwigType_add_pointer(t);
  1164. // Catch all: eg. a class with only static functions and/or variables will not have 'remembered'
  1165. String *wrap_class_name = Swig_name_wrapper(NewStringf("class_%s", mangled_full_proxy_class_name));
  1166. String *wrap_class = NewStringf("&%s", wrap_class_name);
  1167. SwigType_remember_clientdata(t, wrap_class);
  1168. String *rt = Copy(getClassType());
  1169. SwigType_add_pointer(rt);
  1170. // Adding class to appropriate namespace
  1171. registerClass(nspace, wrap_class_name);
  1172. Hash *nspaceHash = getCArraysHash(nspace);
  1173. // Register the class structure with the type checker
  1174. // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_full_proxy_class_name);
  1175. // emit a function to be called to delete the object
  1176. if (have_destructor) {
  1177. destructor_name = NewStringf("swig_delete_%s", mangled_full_proxy_class_name);
  1178. Printv(f_wrappers, "static void ", destructor_name, "(void *obj) {\n", NIL);
  1179. if (destructor_action) {
  1180. Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL);
  1181. Printv(f_wrappers, destructor_action, "\n", NIL);
  1182. } else {
  1183. if (CPlusPlus) {
  1184. Printv(f_wrappers, " delete (", SwigType_str(rt, 0), ") obj;\n", NIL);
  1185. } else {
  1186. Printv(f_wrappers, " free((char *) obj);\n", NIL);
  1187. }
  1188. }
  1189. Printf(f_wrappers, "}\n");
  1190. }
  1191. // Wrap constructor wrapper into one more proxy function. It will be used as class namespace __call method, thus
  1192. // allowing both
  1193. // Module.ClassName.StaticMethod to access static method/variable/constant
  1194. // Module.ClassName() to create new object
  1195. if (have_constructor) {
  1196. assert(constructor_name);
  1197. String *constructor_proxy_name = NewStringf("_proxy_%s", constructor_name);
  1198. Printv(f_wrappers, "static int ", constructor_proxy_name, "(lua_State *L) {\n", NIL);
  1199. Printv(f_wrappers,
  1200. tab4, "assert(lua_istable(L,1));\n",
  1201. tab4, "lua_pushcfunction(L,", constructor_name, ");\n",
  1202. tab4, "assert(!lua_isnil(L,-1));\n",
  1203. tab4, "lua_replace(L,1); /* replace our table with real constructor */\n",
  1204. tab4, "lua_call(L,lua_gettop(L)-1,1);\n",
  1205. tab4, "return 1;\n}\n", NIL);
  1206. Delete(constructor_name);
  1207. constructor_name = constructor_proxy_name;
  1208. if (elua_ltr) {
  1209. String *static_cls_metatable_tab = Getattr(static_cls, "metatable");
  1210. assert(static_cls_metatable_tab);
  1211. Printf(static_cls_metatable_tab, " {LSTRKEY(\"__call\"), LFUNCVAL(%s)},\n", constructor_name);
  1212. } else if (eluac_ltr) {
  1213. String *ns_methods_tab = Getattr(nspaceHash, "methods");
  1214. assert(ns_methods_tab);
  1215. Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "new_", proxy_class_name, "\")", ", LFUNCVAL(", constructor_name, ")", "},\n", NIL);
  1216. }
  1217. }
  1218. if (have_destructor) {
  1219. if (eluac_ltr) {
  1220. String *ns_methods_tab = Getattr(nspaceHash, "methods");
  1221. assert(ns_methods_tab);
  1222. Printv(ns_methods_tab, tab4, "{LSTRKEY(\"", "free_", mangled_full_proxy_class_name, "\")", ", LFUNCVAL(", destructor_name, ")", "},\n", NIL);
  1223. }
  1224. }
  1225. closeCArraysHash(full_proxy_class_name, f_wrappers);
  1226. closeCArraysHash(class_static_nspace, f_wrappers);
  1227. // Handle inheritance
  1228. // note: with the idea of class hierarchies spread over multiple modules
  1229. // cf test-suite: imports.i
  1230. // it is not possible to just add the pointers to the base classes to the code
  1231. // (as sometimes these classes are not present)
  1232. // therefore we instead hold the name of the base class and a null pointer
  1233. // at runtime: we can query the swig type manager & see if the class exists
  1234. // if so, we can get the pointer to the base class & replace the null pointer
  1235. // if the type does not exist, then we cannot...
  1236. String *base_class = NewString("");
  1237. String *base_class_names = NewString("");
  1238. List *baselist = Getattr(n, "bases");
  1239. if (baselist && Len(baselist)) {
  1240. Iterator b;
  1241. b = First(baselist);
  1242. while (b.item) {
  1243. String *bname = Getattr(b.item, "name");
  1244. if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) {
  1245. b = Next(b);
  1246. continue;
  1247. }
  1248. // stores a null pointer & the name
  1249. Printf(base_class, "0,");
  1250. Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname));
  1251. b = Next(b);
  1252. }
  1253. }
  1254. // First, print class static part
  1255. printCArraysDefinition(class_static_nspace, proxy_class_name, f_wrappers);
  1256. assert(mangled_full_proxy_class_name);
  1257. assert(base_class);
  1258. assert(base_class_names);
  1259. assert(proxy_class_name);
  1260. assert(full_proxy_class_name);
  1261. // Then print class instance part
  1262. Printv(f_wrappers, "static swig_lua_class *swig_", mangled_full_proxy_class_name, "_bases[] = {", base_class, "0};\n", NIL);
  1263. Delete(base_class);
  1264. Printv(f_wrappers, "static const char *swig_", mangled_full_proxy_class_name, "_base_names[] = {", base_class_names, "0};\n", NIL);
  1265. Delete(base_class_names);
  1266. Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_full_proxy_class_name, " = { \"", proxy_class_name, "\", \"", full_proxy_class_name, "\", &SWIGTYPE",
  1267. SwigType_manglestr(t), ",", NIL);
  1268. if (have_constructor) {
  1269. Printv(f_wrappers, constructor_name, NIL);
  1270. Delete(constructor_name);
  1271. constructor_name = 0;
  1272. } else {
  1273. Printf(f_wrappers, "0");
  1274. }
  1275. if (have_destructor) {
  1276. Printv(f_wrappers, ", ", destructor_name, NIL);
  1277. } else {
  1278. Printf(f_wrappers, ",0");
  1279. }
  1280. Printf(f_wrappers, ", %s, %s, &%s", s_methods_tab_name, s_attr_tab_name, Getattr(static_cls, "cname"));
  1281. if (!eluac_ltr) {
  1282. Printf(f_wrappers, ", %s", Getattr(instance_cls,"metatable:name"));
  1283. }
  1284. else
  1285. Printf(f_wrappers, ", 0");
  1286. Printf(f_wrappers, ", swig_%s_bases, swig_%s_base_names };\n\n", mangled_full_proxy_class_name, mangled_full_proxy_class_name);
  1287. current[NO_CPP] = true;
  1288. Delete(class_static_nspace);
  1289. class_static_nspace = 0;
  1290. Delete(mangled_full_proxy_class_name);
  1291. mangled_full_proxy_class_name = 0;
  1292. Delete(destructor_name);
  1293. destructor_name = 0;
  1294. Delete(full_proxy_class_name);
  1295. full_proxy_class_name = 0;
  1296. proxy_class_name = 0;
  1297. return SWIG_OK;
  1298. }
  1299. /* ------------------------------------------------------------
  1300. * memberfunctionHandler()
  1301. * ------------------------------------------------------------ */
  1302. virtual int memberfunctionHandler(Node *n) {
  1303. String *symname = GetChar(n, "sym:name");
  1304. //Printf(stdout,"memberfunctionHandler %s %s\n",name,iname);
  1305. // Special case unary minus: LUA passes two parameters for the
  1306. // wrapper function while we want only one. Tell our
  1307. // functionWrapper to ignore a parameter.
  1308. if (Cmp(symname, "__unm") == 0) {
  1309. //Printf(stdout, "unary minus: ignore one argument\n");
  1310. SetInt(n, "lua:ignore_args", 1);
  1311. }
  1312. current[MEMBER_FUNC] = true;
  1313. Language::memberfunctionHandler(n);
  1314. registerMethod(n);
  1315. current[MEMBER_FUNC] = false;
  1316. return SWIG_OK;
  1317. }
  1318. /* ------------------------------------------------------------
  1319. * membervariableHandler()
  1320. * ------------------------------------------------------------ */
  1321. virtual int membervariableHandler(Node *n) {
  1322. // REPORT("membervariableHandler",n);
  1323. current[MEMBER_VAR] = true;
  1324. Language::membervariableHandler(n);
  1325. registerVariable(n);
  1326. current[MEMBER_VAR] = false;
  1327. return SWIG_OK;
  1328. }
  1329. /* ------------------------------------------------------------
  1330. * constructorHandler()
  1331. *
  1332. * Method for adding C++ member constructor
  1333. * ------------------------------------------------------------ */
  1334. virtual int constructorHandler(Node *n) {
  1335. // REPORT("constructorHandler", n);
  1336. current[CONSTRUCTOR] = true;
  1337. Language::constructorHandler(n);
  1338. current[CONSTRUCTOR] = false;
  1339. //constructor_name = NewString(Getattr(n, "sym:name"));
  1340. have_constructor = 1;
  1341. return SWIG_OK;
  1342. }
  1343. /* ------------------------------------------------------------
  1344. * destructorHandler()
  1345. * ------------------------------------------------------------ */
  1346. virtual int destructorHandler(Node *n) {
  1347. REPORT("destructorHandler", n);
  1348. current[DESTRUCTOR] = true;
  1349. Language::destructorHandler(n);
  1350. current[DESTRUCTOR] = false;
  1351. have_destructor = 1;
  1352. destructor_action = Getattr(n, "wrap:action");
  1353. return SWIG_OK;
  1354. }
  1355. /* ----------------------------------------------------------------------
  1356. * globalfunctionHandler()
  1357. *
  1358. * It can be called:
  1359. * 1. Usual C/C++ global function.
  1360. * 2. During class parsing for functions declared/defined as friend
  1361. * 3. During class parsing from staticmemberfunctionHandler
  1362. * ---------------------------------------------------------------------- */
  1363. virtual int globalfunctionHandler(Node *n) {
  1364. bool oldVal = current[NO_CPP];
  1365. if (!current[STATIC_FUNC]) // If static function, don't switch to NO_CPP
  1366. current[NO_CPP] = true;
  1367. const int result = Language::globalfunctionHandler(n);
  1368. if (!current[STATIC_FUNC]) // Register only if not called from static function handler
  1369. registerMethod(n);
  1370. current[NO_CPP] = oldVal;
  1371. return result;
  1372. }
  1373. /* ----------------------------------------------------------------------
  1374. * globalvariableHandler()
  1375. *
  1376. * Sets "current" array correctly
  1377. * ---------------------------------------------------------------------- */
  1378. virtual int globalvariableHandler(Node *n) {
  1379. bool oldVal = current[NO_CPP];
  1380. current[GLOBAL_VAR] = true;
  1381. current[NO_CPP] = true;
  1382. const int result = Language::globalvariableHandler(n);
  1383. registerVariable(n);
  1384. current[GLOBAL_VAR] = false;
  1385. current[NO_CPP] = oldVal;
  1386. return result;
  1387. }
  1388. /* -----------------------------------------------------------------------
  1389. * staticmemberfunctionHandler()
  1390. *
  1391. * Wrap a static C++ function
  1392. * ---------------------------------------------------------------------- */
  1393. virtual int staticmemberfunctionHandler(Node *n) {
  1394. REPORT("staticmemberfunctionHandler", n);
  1395. current[STATIC_FUNC] = true;
  1396. const int result = Language::staticmemberfunctionHandler(n);
  1397. registerMethod(n);
  1398. if (old_metatable_bindings && result == SWIG_OK && old_compatible_names) {
  1399. Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL);
  1400. String *lua_name = Getattr(n, "lua:name");
  1401. // Although this function uses Swig_name_member, it actually generates the Lua name,
  1402. // not the C++ name. This is because an earlier version used such a scheme for static function
  1403. // name generation and we have to maintain backward compatibility.
  1404. String *compat_name = Swig_name_member(0, proxy_class_name, lua_name);
  1405. Setattr(n, "lua:name", compat_name);
  1406. registerMethod(n, true, getNSpace());
  1407. Delete(compat_name);
  1408. Swig_restore(n);
  1409. }
  1410. current[STATIC_FUNC] = false;;
  1411. return result;
  1412. }
  1413. /* ------------------------------------------------------------
  1414. * memberconstantHandler()
  1415. *
  1416. * Create a C++ constant
  1417. * ------------------------------------------------------------ */
  1418. virtual int memberconstantHandler(Node *n) {
  1419. REPORT("memberconstantHandler", n);
  1420. int result = Language::memberconstantHandler(n);
  1421. return result;
  1422. }
  1423. /* ---------------------------------------------------------------------
  1424. * staticmembervariableHandler()
  1425. * --------------------------------------------------------------------- */
  1426. virtual int staticmembervariableHandler(Node *n) {
  1427. REPORT("staticmembervariableHandler", n);
  1428. current[STATIC_VAR] = true;
  1429. //String *symname = Getattr(n, "sym:name");
  1430. int result = Language::staticmembervariableHandler(n);
  1431. if (!GetFlag(n, "wrappedasconstant")) {
  1432. registerVariable(n);
  1433. }
  1434. if (result == SWIG_OK) {
  1435. // This will add static member variable to the class namespace with name ClassName_VarName
  1436. if (old_metatable_bindings && old_compatible_names) {
  1437. Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL);
  1438. String *lua_name = Getattr(n, "lua:name");
  1439. // Although this function uses Swig_name_member, it actually generates the Lua name,
  1440. // not the C++ name. This is because an earlier version used such a scheme for static function
  1441. // name generation and we have to maintain backward compatibility.
  1442. String *v2_name = Swig_name_member(NIL, proxy_class_name, lua_name);
  1443. if (!GetFlag(n, "wrappedasconstant")) {
  1444. Setattr(n, "lua:name", v2_name);
  1445. // Registering static var in the class parent nspace
  1446. registerVariable(n, true, getNSpace());
  1447. }
  1448. // If static member variable was wrapped as a constant, then
  1449. // constant wrapper has already performed all actions necessary for old_metatable_bindings
  1450. Delete(v2_name);
  1451. Swig_restore(n);
  1452. }
  1453. }
  1454. current[STATIC_VAR] = false;
  1455. return result;
  1456. }
  1457. /* ---------------------------------------------------------------------
  1458. * external runtime generation
  1459. * --------------------------------------------------------------------- */
  1460. /* This is to support the usage
  1461. SWIG -external-runtime <filename>
  1462. The code consists of two functions:
  1463. String *runtimeCode() // returns a large string with all the runtimes in
  1464. String *defaultExternalRuntimeFilename() // returns the default filename
  1465. I am writing a generic solution, even though SWIG-Lua only has one file right now...
  1466. */
  1467. String *runtimeCode() {
  1468. String *s = NewString("");
  1469. const char *filenames[] = { "luarun.swg", 0 }; // must be 0 terminated
  1470. emitLuaFlavor(s);
  1471. String *sfile = 0;
  1472. for (int i = 0; filenames[i] != 0; i++) {
  1473. sfile = Swig_include_sys(filenames[i]);
  1474. if (!sfile) {
  1475. Printf(stderr, "*** Unable to open '%s'\n", filenames[i]);
  1476. } else {
  1477. Append(s, sfile);
  1478. Delete(sfile);
  1479. }
  1480. }
  1481. return s;
  1482. }
  1483. String *defaultExternalRuntimeFilename() {
  1484. return NewString("swigluarun.h");
  1485. }
  1486. /* ---------------------------------------------------------------------
  1487. * helpers
  1488. * --------------------------------------------------------------------- */
  1489. void emitLuaFlavor(String *s) {
  1490. if (elua_emulate) {
  1491. Printf(s, "/*This is only emulation!*/\n");
  1492. Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUA\n");
  1493. Printf(s, "#define SWIG_LUA_ELUA_EMULATE\n");
  1494. } else if (elua_ltr)
  1495. Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUA\n");
  1496. else if (eluac_ltr)
  1497. Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_ELUAC\n");
  1498. else
  1499. Printf(s, "#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_LUA\n");
  1500. }
  1501. /* -----------------------------------------------------------------------------
  1502. * escapeCode()
  1503. *
  1504. * This is to convert the string of Lua code into a proper string, which can then be
  1505. * emitted into the C/C++ code.
  1506. * Basically it is a lot of search & replacing of odd sequences
  1507. * ---------------------------------------------------------------------------- */
  1508. void escapeCode(String *str) {
  1509. //Printf(f_runtime,"/* original luacode:[[[\n%s\n]]]\n*/\n",str);
  1510. Chop(str); // trim
  1511. Replace(str, "\\", "\\\\", DOH_REPLACE_ANY); // \ to \\ (this must be done first)
  1512. Replace(str, "\"", "\\\"", DOH_REPLACE_ANY); // " to \"
  1513. Replace(str, "\n", "\\n\"\n \"", DOH_REPLACE_ANY); // \n to \n"\n" (ie quoting every line)
  1514. //Printf(f_runtime,"/* hacked luacode:[[[\n%s\n]]]\n*/\n",str);
  1515. }
  1516. /* -----------------------------------------------------------------------------
  1517. * rawGetCArraysHash(String *name)
  1518. *
  1519. * A small helper to hide implementation of how CArrays hashes are stored
  1520. * ---------------------------------------------------------------------------- */
  1521. Hash *rawGetCArraysHash(const_String_or_char_ptr name) {
  1522. Hash *scope = symbolScopeLookup( name ? name : "" );
  1523. if(!scope)
  1524. return 0;
  1525. Hash *carrays_hash = Getattr(scope, "lua:cdata");
  1526. return carrays_hash;
  1527. }
  1528. /* -----------------------------------------------------------------------------
  1529. * getCArraysHash()
  1530. *
  1531. * Each namespace can be described with a hash that stores C arrays
  1532. * where members of the namespace should be added. All these hashes are stored
  1533. * inside the symbols table, in pseudo-symbol for every namespace.
  1534. * nspace could be NULL (NSPACE_TODO), that means functions and variables and classes
  1535. * that are not in any namespace (this is default for SWIG unless %nspace feature is used).
  1536. * You can later set some attributes that will affect behaviour of functions that use this hash:
  1537. * "lua:no_namespaces" will disable "namespaces" array.
  1538. * "lua:no_classes" will disable "classes" array.
  1539. * For every component ("attributes", "methods", etc) there are subcomponents:
  1540. * XXX:name - name of the C array that stores data for component
  1541. * XXX:decl - statement with forward declaration of this array;
  1542. * Namespace could be automatically registered to its parent if 'reg' == true. This can only be
  1543. * done during the first call (a.k.a when nspace is created).
  1544. * ---------------------------------------------------------------------------- */
  1545. Hash *getCArraysHash(String *nspace, bool reg = true) {
  1546. Hash *scope = symbolScopeLookup(nspace ? nspace : "");
  1547. if(!scope) {
  1548. symbolAddScope( nspace ? nspace : "" );
  1549. scope = symbolScopeLookup(nspace ? nspace : "");
  1550. assert(scope);
  1551. }
  1552. Hash *carrays_hash = Getattr(scope, "lua:cdata");
  1553. if (carrays_hash != 0)
  1554. return carrays_hash;
  1555. carrays_hash = NewHash();
  1556. String *mangled_name = 0;
  1557. if (nspace == 0 || Len(nspace) == 0)
  1558. mangled_name = NewString("SwigModule");
  1559. else
  1560. mangled_name = Swig_name_mangle(nspace);
  1561. String *cname = NewStringf("swig_%s", mangled_name);
  1562. Setattr(carrays_hash, "cname", cname);
  1563. String *attr_tab = NewString("");
  1564. String *attr_tab_name = NewStringf("swig_%s_attributes", mangled_name);
  1565. String *attr_tab_decl = NewString("");
  1566. Printv(attr_tab, "static swig_lua_attribute ", NIL);
  1567. Printv(attr_tab, attr_tab_name, "[]", NIL);
  1568. Printv(attr_tab_decl, attr_tab, ";\n", NIL);
  1569. Printv(attr_tab, " = {\n", NIL);
  1570. Setattr(carrays_hash, "attributes", attr_tab);
  1571. Setattr(carrays_hash, "attributes:name", attr_tab_name);
  1572. Setattr(carrays_hash, "attributes:decl", attr_tab_decl);
  1573. String *methods_tab = NewString("");
  1574. String *methods_tab_name = NewStringf("swig_%s_methods", mangled_name);
  1575. String *methods_tab_decl = NewString("");
  1576. if (elua_ltr || eluac_ltr) // In this case methods array also acts as namespace rotable
  1577. Printf(methods_tab, "const LUA_REG_TYPE ");
  1578. else
  1579. Printf(methods_tab, "static swig_lua_method ");
  1580. Printv(methods_tab, methods_tab_name, "[]", NIL);
  1581. Printv(methods_tab_decl, methods_tab, ";\n", NIL);
  1582. Printv(methods_tab, "= {\n", NIL);
  1583. Setattr(carrays_hash, "methods", methods_tab);
  1584. Setattr(carrays_hash, "methods:name", methods_tab_name);
  1585. Setattr(carrays_hash, "methods:decl", methods_tab_decl);
  1586. String *const_tab = NewString("");
  1587. String *const_tab_name = NewStringf("swig_%s_constants", mangled_name);
  1588. String *const_tab_decl = NewString("");
  1589. if (elua_ltr || eluac_ltr) // In this case const array holds rotable with namespace constants
  1590. Printf(const_tab, "const LUA_REG_TYPE ");
  1591. else
  1592. Printf(const_tab, "static swig_lua_const_info ");
  1593. Printv(const_tab, const_tab_name, "[]", NIL);
  1594. Printv(const_tab_decl, const_tab, ";", NIL);
  1595. Printv(const_tab, "= {\n", NIL);
  1596. Setattr(carrays_hash, "constants", const_tab);
  1597. Setattr(carrays_hash, "constants:name", const_tab_name);
  1598. Setattr(carrays_hash, "constants:decl", const_tab_decl);
  1599. String *classes_tab = NewString("");
  1600. String *classes_tab_name = NewStringf("swig_%s_classes", mangled_name);
  1601. String *classes_tab_decl = NewString("");
  1602. Printf(classes_tab, "static swig_lua_class* ");
  1603. Printv(classes_tab, classes_tab_name, "[]", NIL);
  1604. Printv(classes_tab_decl, classes_tab, ";", NIL);
  1605. Printv(classes_tab, "= {\n", NIL);
  1606. Setattr(carrays_hash, "classes", classes_tab);
  1607. Setattr(carrays_hash, "classes:name", classes_tab_name);
  1608. Setattr(carrays_hash, "classes:decl", classes_tab_decl);
  1609. String *namespaces_tab = NewString("");
  1610. String *namespaces_tab_name = NewStringf("swig_%s_namespaces", mangled_name);
  1611. String *namespaces_tab_decl = NewString("");
  1612. Printf(namespaces_tab, "static swig_lua_namespace* ");
  1613. Printv(namespaces_tab, namespaces_tab_name, "[]", NIL);
  1614. Printv(namespaces_tab_decl, namespaces_tab, ";", NIL);
  1615. Printv(namespaces_tab, " = {\n", NIL);
  1616. Setattr(carrays_hash, "namespaces", namespaces_tab);
  1617. Setattr(carrays_hash, "namespaces:name", namespaces_tab_name);
  1618. Setattr(carrays_hash, "namespaces:decl", namespaces_tab_decl);
  1619. if (elua_ltr) {
  1620. String *get_tab = NewString("");
  1621. String *get_tab_name = NewStringf("swig_%s_get", mangled_name);
  1622. String *get_tab_decl = NewString("");
  1623. Printv(get_tab, "const LUA_REG_TYPE ", get_tab_name, "[]", NIL);
  1624. Printv(get_tab_decl, get_tab, ";", NIL);
  1625. Printv(get_tab, " = {\n", NIL);
  1626. Setattr(carrays_hash, "get", get_tab);
  1627. Setattr(carrays_hash, "get:name", get_tab_name);
  1628. Setattr(carrays_hash, "get:decl", get_tab_decl);
  1629. String *set_tab = NewString("");
  1630. String *set_tab_name = NewStringf("swig_%s_set", mangled_name);
  1631. String *set_tab_decl = NewString("");
  1632. Printv(set_tab, "const LUA_REG_TYPE ", set_tab_name, "[]", NIL);
  1633. Printv(set_tab_decl, set_tab, ";", NIL);
  1634. Printv(set_tab, " = {\n", NIL);
  1635. Setattr(carrays_hash, "set", set_tab);
  1636. Setattr(carrays_hash, "set:name", set_tab_name);
  1637. Setattr(carrays_hash, "set:decl", set_tab_decl);
  1638. }
  1639. if (!eluac_ltr) {
  1640. String *metatable_tab = NewString("");
  1641. String *metatable_tab_name = NewStringf("swig_%s_meta", mangled_name);
  1642. String *metatable_tab_decl = NewString("");
  1643. if (elua_ltr) // In this case const array holds rotable with namespace constants
  1644. Printf(metatable_tab, "const LUA_REG_TYPE ");
  1645. else
  1646. Printf(metatable_tab, "static swig_lua_method ");
  1647. Printv(metatable_tab, metatable_tab_name, "[]", NIL);
  1648. Printv(metatable_tab_decl, metatable_tab, ";", NIL);
  1649. Printv(metatable_tab, " = {\n", NIL);
  1650. Setattr(carrays_hash, "metatable", metatable_tab);
  1651. Setattr(carrays_hash, "metatable:name", metatable_tab_name);
  1652. Setattr(carrays_hash, "metatable:decl", metatable_tab_decl);
  1653. }
  1654. Setattr(scope, "lua:cdata", carrays_hash);
  1655. assert(rawGetCArraysHash(nspace));
  1656. if (reg && nspace != 0 && Len(nspace) != 0 && GetFlag(carrays_hash, "lua:no_reg") == 0) {
  1657. // Split names into components
  1658. List *components = Split(nspace, '.', -1);
  1659. String *parent_path = NewString("");
  1660. int len = Len(components);
  1661. String *name = Copy(Getitem(components, len - 1));
  1662. for (int i = 0; i < len - 1; i++) {
  1663. if (i > 0)
  1664. Printv(parent_path, NSPACE_SEPARATOR, NIL);
  1665. String *item = Getitem(components, i);
  1666. Printv(parent_path, item, NIL);
  1667. }
  1668. Hash *parent = getCArraysHash(parent_path, true);
  1669. String *namespaces_tab = Getattr(parent, "namespaces");
  1670. Printv(namespaces_tab, "&", cname, ",\n", NIL);
  1671. if (elua_ltr || eluac_ltr) {
  1672. String *methods_tab = Getattr(parent, "methods");
  1673. Printv(methods_tab, tab4, "{LSTRKEY(\"", name, "\")", ", LROVAL(", methods_tab_name, ")", "},\n", NIL);
  1674. }
  1675. Setattr(carrays_hash, "name", name);
  1676. Delete(components);
  1677. Delete(parent_path);
  1678. } else if (!reg) // This namespace shouldn't be registered. Lets remember it.
  1679. SetFlag(carrays_hash, "lua:no_reg");
  1680. Delete(mangled_name);
  1681. mangled_name = 0;
  1682. return carrays_hash;
  1683. }
  1684. /* -----------------------------------------------------------------------------
  1685. * closeCArraysHash()
  1686. *
  1687. * Functions add end markers {0,0,...,0} to all arrays, prints them to
  1688. * output and marks hash as closed (lua:closed). Consequent attempts to
  1689. * close the same hash will result in an error.
  1690. * closeCArraysHash DOES NOT print structure that describes namespace, it only
  1691. * prints array. You can use printCArraysDefinition to print structure.
  1692. * if "lua:no_namespaces" is set, then array for "namespaces" won't be printed
  1693. * if "lua:no_classes" is set, then array for "classes" won't be printed
  1694. * ----------------------------------------------------------------------------- */
  1695. void closeCArraysHash(String *nspace, File *output) {
  1696. Hash *carrays_hash = rawGetCArraysHash(nspace);
  1697. assert(carrays_hash);
  1698. assert(GetFlag(carrays_hash, "lua:closed") == 0);
  1699. SetFlag(carrays_hash, "lua:closed");
  1700. // Do arrays describe class instance part or class static part
  1701. const int is_instance = GetFlag(carrays_hash, "lua:class_instance");
  1702. String *attr_tab = Getattr(carrays_hash, "attributes");
  1703. Printf(attr_tab, " {0,0,0}\n};\n");
  1704. Printv(output, attr_tab, NIL);
  1705. String *const_tab = Getattr(carrays_hash, "constants");
  1706. String *const_tab_name = Getattr(carrays_hash, "constants:name");
  1707. if (elua_ltr || eluac_ltr)
  1708. Printv(const_tab, tab4, "{LNILKEY, LNILVAL}\n", "};\n", NIL);
  1709. else
  1710. Printf(const_tab, " {0,0,0,0,0,0}\n};\n");
  1711. // For the sake of compiling with -Wall -Werror we print constants
  1712. // only when necessary
  1713. int need_constants = 0;
  1714. if ( (elua_ltr || eluac_ltr) && (old_metatable_bindings) )
  1715. need_constants = 1;
  1716. else if (!is_instance) // static part need constants tab
  1717. need_constants = 1;
  1718. if (need_constants)
  1719. Printv(output, const_tab, NIL);
  1720. if (elua_ltr) {
  1721. // Put forward declaration of metatable array
  1722. Printv(output, "extern ", Getattr(carrays_hash, "metatable:decl"), "\n", NIL);
  1723. }
  1724. String *methods_tab = Getattr(carrays_hash, "methods");
  1725. String *metatable_tab_name = Getattr(carrays_hash, "metatable:name");
  1726. if (elua_ltr || eluac_ltr) {
  1727. if (old_metatable_bindings)
  1728. Printv(methods_tab, tab4, "{LSTRKEY(\"const\"), LROVAL(", const_tab_name, ")},\n", NIL);
  1729. if (elua_ltr) {
  1730. Printv(methods_tab, tab4, "{LSTRKEY(\"__metatable\"), LROVAL(", metatable_tab_name, ")},\n", NIL);
  1731. }
  1732. Printv(methods_tab, tab4, "{LSTRKEY(\"__disown\"), LFUNCVAL(SWIG_Lua_class_disown)},\n", NIL);
  1733. Printv(methods_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL);
  1734. } else
  1735. Printf(methods_tab, " {0,0}\n};\n");
  1736. Printv(output, methods_tab, NIL);
  1737. if (!GetFlag(carrays_hash, "lua:no_classes")) {
  1738. String *classes_tab = Getattr(carrays_hash, "classes");
  1739. Printf(classes_tab, " 0\n};\n");
  1740. Printv(output, classes_tab, NIL);
  1741. }
  1742. if (!GetFlag(carrays_hash, "lua:no_namespaces")) {
  1743. String *namespaces_tab = Getattr(carrays_hash, "namespaces");
  1744. Printf(namespaces_tab, " 0\n};\n");
  1745. Printv(output, namespaces_tab, NIL);
  1746. }
  1747. if (elua_ltr) {
  1748. String *get_tab = Getattr(carrays_hash, "get");
  1749. String *set_tab = Getattr(carrays_hash, "set");
  1750. Printv(get_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL);
  1751. Printv(set_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL);
  1752. Printv(output, get_tab, NIL);
  1753. Printv(output, set_tab, NIL);
  1754. }
  1755. // Heuristic whether we need to print metatable or not.
  1756. // For the sake of compiling with -Wall -Werror we don't print
  1757. // metatable for static part.
  1758. int need_metatable = 0;
  1759. if (eluac_ltr)
  1760. need_metatable = 0;
  1761. else if(!is_instance)
  1762. need_metatable = 0;
  1763. else
  1764. need_metatable = 1;
  1765. if (need_metatable) {
  1766. String *metatable_tab = Getattr(carrays_hash, "metatable");
  1767. assert(metatable_tab);
  1768. if (elua_ltr) {
  1769. String *get_tab_name = Getattr(carrays_hash, "get:name");
  1770. String *set_tab_name = Getattr(carrays_hash, "set:name");
  1771. if (GetFlag(carrays_hash, "lua:class_instance")) {
  1772. Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_class_get)},\n", NIL);
  1773. Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_class_set)},\n", NIL);
  1774. } else {
  1775. Printv(metatable_tab, tab4, "{LSTRKEY(\"__index\"), LFUNCVAL(SWIG_Lua_namespace_get)},\n", NIL);
  1776. Printv(metatable_tab, tab4, "{LSTRKEY(\"__newindex\"), LFUNCVAL(SWIG_Lua_namespace_set)},\n", NIL);
  1777. }
  1778. Printv(metatable_tab, tab4, "{LSTRKEY(\"__gc\"), LFUNCVAL(SWIG_Lua_class_destruct)},\n", NIL);
  1779. Printv(metatable_tab, tab4, "{LSTRKEY(\".get\"), LROVAL(", get_tab_name, ")},\n", NIL);
  1780. Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL);
  1781. Printv(metatable_tab, tab4, "{LSTRKEY(\".fn\"), LROVAL(", Getattr(carrays_hash, "methods:name"), ")},\n", NIL);
  1782. if (GetFlag(carrays_hash, "lua:class_instance")) {
  1783. String *static_cls = Getattr(carrays_hash, "lua:class_instance:static_hash");
  1784. assert(static_cls);
  1785. // static_cls is swig_lua_namespace. This structure can't be used with eLua(LTR)
  1786. // Instead a structure describing its methods is used
  1787. String *static_cls_cname = Getattr(static_cls, "methods:name");
  1788. assert(static_cls_cname);
  1789. Printv(metatable_tab, tab4, "{LSTRKEY(\".static\"), LROVAL(", static_cls_cname, ")},\n", NIL);
  1790. // Put forward declaration of this array
  1791. Printv(output, "extern ", Getattr(static_cls, "methods:decl"), "\n", NIL);
  1792. } else if (GetFlag(carrays_hash, "lua:class_static")) {
  1793. Hash *instance_cls = Getattr(carrays_hash, "lua:class_static:instance_hash");
  1794. assert(instance_cls);
  1795. String *instance_cls_metatable_name = Getattr(instance_cls, "metatable:name");
  1796. assert(instance_cls_metatable_name);
  1797. Printv(metatable_tab, tab4, "{LSTRKEY(\".instance\"), LROVAL(", instance_cls_metatable_name, ")},\n", NIL);
  1798. }
  1799. Printv(metatable_tab, tab4, "{LNILKEY, LNILVAL}\n};\n", NIL);
  1800. } else {
  1801. Printf(metatable_tab, " {0,0}\n};\n");
  1802. }
  1803. Printv(output, metatable_tab, NIL);
  1804. }
  1805. Printv(output, "\n", NIL);
  1806. }
  1807. /* -----------------------------------------------------------------------------
  1808. * closeNamespaces()
  1809. *
  1810. * Recursively close all non-closed namespaces. Prints data to dataOutput.
  1811. * ----------------------------------------------------------------------------- */
  1812. void closeNamespaces(File *dataOutput) {
  1813. // Special handling for empty module.
  1814. if (symbolScopeLookup("") == 0 || rawGetCArraysHash("") == 0) {
  1815. // Module is empty. Create hash for global scope in order to have swig_SwigModule
  1816. // variable in resulting file
  1817. getCArraysHash(0);
  1818. }
  1819. // Because we can't directly access 'symtabs', instead we access
  1820. // top-level scope and look on all scope pseudo-symbols in it.
  1821. Hash *top_scope = symbolScopeLookup("");
  1822. assert(top_scope);
  1823. Iterator ki = First(top_scope);
  1824. List *to_close = NewList();
  1825. while (ki.key) {
  1826. assert(ki.item);
  1827. if (Getattr(ki.item, "sym:scope")) {
  1828. // We have a pseudo symbol. Lets get actual scope for this pseudo symbol
  1829. Hash *carrays_hash = rawGetCArraysHash(ki.key);
  1830. assert(carrays_hash);
  1831. if (GetFlag(carrays_hash, "lua:closed") == 0)
  1832. Append(to_close, ki.key);
  1833. }
  1834. ki = Next(ki);
  1835. }
  1836. SortList(to_close, &compareByLen);
  1837. int len = Len(to_close);
  1838. for (int i = 0; i < len; i++) {
  1839. String *key = Getitem(to_close, i);
  1840. closeCArraysHash(key, dataOutput);
  1841. Hash *carrays_hash = rawGetCArraysHash(key);
  1842. String *name = 0; // name - name of the namespace as it should be visible in Lua
  1843. if (DohLen(key) == 0) // This is global module
  1844. name = module;
  1845. else
  1846. name = Getattr(carrays_hash, "name");
  1847. assert(name);
  1848. printCArraysDefinition(key, name, dataOutput);
  1849. }
  1850. Delete(to_close);
  1851. }
  1852. /* -----------------------------------------------------------------------------
  1853. * printCArraysDefinition()
  1854. *
  1855. * This function prints to output a definition of namespace in form
  1856. * swig_lua_namespace $cname = { attr_array, methods_array, ... , namespaces_array };
  1857. * You can call this function as many times as is necessary.
  1858. * 'name' is a user-visible name that this namespace will have in Lua. It shouldn't
  1859. * be a fully qualified name, just its own name.
  1860. * ----------------------------------------------------------------------------- */
  1861. void printCArraysDefinition(String *nspace, String *name, File *output) {
  1862. Hash *carrays_hash = getCArraysHash(nspace, false);
  1863. String *cname = Getattr(carrays_hash, "cname"); // cname - name of the C structure that describes namespace
  1864. assert(cname);
  1865. Printv(output, "static swig_lua_namespace ", cname, " = ", NIL);
  1866. String *null_string = NewString("0");
  1867. String *attr_tab_name = Getattr(carrays_hash, "attributes:name");
  1868. String *methods_tab_name = Getattr(carrays_hash, "methods:name");
  1869. String *const_tab_name = Getattr(carrays_hash, "constants:name");
  1870. String *classes_tab_name = Getattr(carrays_hash, "classes:name");
  1871. String *namespaces_tab_name = Getattr(carrays_hash, "namespaces:name");
  1872. bool has_classes = GetFlag(carrays_hash, "lua:no_classes") == 0;
  1873. bool has_namespaces = GetFlag(carrays_hash, "lua:no_namespaces") == 0;
  1874. Printv(output, "{\n",
  1875. tab4, "\"", name, "\",\n",
  1876. tab4, methods_tab_name, ",\n",
  1877. tab4, attr_tab_name, ",\n",
  1878. tab4, const_tab_name, ",\n",
  1879. tab4, (has_classes) ? classes_tab_name : null_string, ",\n",
  1880. tab4, (has_namespaces) ? namespaces_tab_name : null_string, "\n};\n", NIL);
  1881. Delete(null_string);
  1882. }
  1883. /* -----------------------------------------------------------------------------
  1884. * luaCurrentSymbolNSpace()
  1885. *
  1886. * This function determines actual namespace/scope where any symbol at the
  1887. * current moment should be placed. It looks at the 'current' array
  1888. * and depending on where are we - static class member/function,
  1889. * instance class member/function or just global functions decides
  1890. * where symbol should be put.
  1891. * The namespace/scope doesn't depend from symbol, only from 'current'
  1892. * ----------------------------------------------------------------------------- */
  1893. String *luaCurrentSymbolNSpace() {
  1894. String *scope = 0;
  1895. // If outside class, than NSpace is used.
  1896. // If inside class, but current[NO_CPP], then this is friend function. It belongs to NSpace
  1897. if (!getCurrentClass() || current[NO_CPP]) {
  1898. scope = getNSpace();
  1899. } else if (current[ENUM_CONST] && !CPlusPlus ) {
  1900. // Enums in C mode go to NSpace
  1901. scope = getNSpace();
  1902. } else {
  1903. // If inside class, then either class static namespace or class fully qualified name is used
  1904. assert(!current[NO_CPP]);
  1905. if (current[STATIC_FUNC] || current[STATIC_VAR] || current[STATIC_CONST]) {
  1906. scope = class_static_nspace;
  1907. } else if (current[MEMBER_VAR] || current[CONSTRUCTOR] || current[DESTRUCTOR]
  1908. || current[MEMBER_FUNC]) {
  1909. scope = full_proxy_class_name;
  1910. } else { // Friend functions are handled this way
  1911. scope = class_static_nspace;
  1912. }
  1913. assert(scope);
  1914. }
  1915. return scope;
  1916. }
  1917. /* -----------------------------------------------------------------------------
  1918. * luaAddSymbol()
  1919. *
  1920. * Our implementation of addSymbol. Determines scope correctly, then
  1921. * forwards to Language::addSymbol
  1922. * ----------------------------------------------------------------------------- */
  1923. int luaAddSymbol(const String *s, const Node *n) {
  1924. String *scope = luaCurrentSymbolNSpace();
  1925. return luaAddSymbol(s, n, scope);
  1926. }
  1927. /* -----------------------------------------------------------------------------
  1928. * luaAddSymbol()
  1929. *
  1930. * Overload. Enforces given scope. Actually, it simply forwards call to Language::addSymbol
  1931. * ----------------------------------------------------------------------------- */
  1932. int luaAddSymbol(const String *s, const Node *n, const_String_or_char_ptr scope) {
  1933. int result = Language::addSymbol(s, n, scope);
  1934. if (!result)
  1935. Printf(stderr, "addSymbol(%s to scope %s) failed\n", s, scope);
  1936. return result;
  1937. }
  1938. };
  1939. /* -----------------------------------------------------------------------------
  1940. * swig_lua() - Instantiate module
  1941. * ----------------------------------------------------------------------------- */
  1942. extern "C" Language *swig_lua(void) {
  1943. return new LUA();
  1944. }