/
lua.cxx
2085 lines (1831 loc) · 79 KB
/
lua.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -----------------------------------------------------------------------------
* This file is part of SWIG, which is licensed as a whole under version 3
* (or any later version) of the GNU General Public License. Some additional
* terms also apply to certain portions of SWIG. The full details of the SWIG
* license and copyrights can be found in the LICENSE and COPYRIGHT files
* included with the SWIG source code as distributed by the SWIG developers
* and at http://www.swig.org/legal.html.
*
* lua.cxx
*
* Lua language module for SWIG.
* ----------------------------------------------------------------------------- */
/* NEW LANGUAGE NOTE:
* ver001
this is simply a copy of tcl8.cxx, which has been renamed
* ver002
all non essential code commented out, program now does virtually nothing
it prints to stderr the list of functions to wrap, but does not create
the XXX_wrap.c file
* ver003
added back top(), still prints the list of fns to stderr
but now creates a rather empty XXX_wrap.c with some basic boilerplate code
* ver004
very basic version of functionWrapper()
also uncommented usage_string() to keep compiler happy
this will start producing proper looking code soon (I hope)
produced the wrapper code, but without any type conversion (in or out)
generates a few warning because of no wrappering
does not generate SWIG_init()
reason for this is that lua.swg is empty
we will need to add code into this to make it work
* ver005/6
massive rework, basing work on the pike module instead of tcl
(pike module it only 1/3 of the size)(though not as complete)
* ver007
added simple type checking
* ver008
INPUT, OUTPUT, INOUT typemaps handled (though not all types yet)
* ver009
class support: ok for basic types, but methods still TDB
(code is VERY messed up & needs to be cleaned)
* ver010
Added support for embedded Lua. Try swig -lua -help for more information
*/
#include "swigmod.h"
#include "cparse.h"
/**** Diagnostics:
With the #define REPORT(), you can change the amount of diagnostics given
This helps me search the parse tree & figure out what is going on inside SWIG
(because its not clear or documented)
*/
#define REPORT(T,D) // no info:
//#define REPORT(T,D) {Printf(stdout,T"\n");} // only title
//#define REPORT(T,D) {Printf(stdout,T" %p\n",n);} // title & pointer
//#define REPORT(T,D) {Printf(stdout,T"\n");display_mapping(D);} // the works
//#define REPORT(T,D) {Printf(stdout,T"\n");if(D)Swig_print_node(D);} // the works
void display_mapping(DOH *d) {
if (d == 0 || !DohIsMapping(d))
return;
for (Iterator it = First(d); it.item; it = Next(it)) {
if (DohIsString(it.item))
Printf(stdout, " %s = %s\n", it.key, it.item);
else if (DohIsMapping(it.item))
Printf(stdout, " %s = <mapping>\n", it.key);
else if (DohIsSequence(it.item))
Printf(stdout, " %s = <sequence>\n", it.key);
else
Printf(stdout, " %s = <unknown>\n", it.key);
}
}
/* NEW LANGUAGE NOTE:***********************************************
most of the default options are handled by SWIG
you can add new ones here
(though for now I have not bothered)
NEW LANGUAGE NOTE:END ************************************************/
static const char *usage = (char *) "\
Lua Options (available with -lua)\n\
-elua [NUM] - Generates LTR compatible wrappers for smaller devices running elua\n\
Optional NUM is default value for MIN_OPT_LEVEL\n\
-eluac [NUM] - LTR compatible wrappers in \"crass compress\" mode for elua\n\
Optional NUM is default value for MIN_OPT_LEVEL\n\
-nomoduleglobal - Do not register the module name as a global variable \n\
but return the module table from calls to require.\n\
-swig3 - Disable support for old-style bindings name generation.\n\
-squash-bases - Squashes symbols from all inheritance tree of a given class\n\
into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly\n\
speeds things up, but increases memory consumption.\n\
\n";
static int nomoduleglobal = 0;
static int elua_ltr = 0;
static int elua_opt_lvl = 2;
static int eluac_ltr = 0;
static int squash_bases = 0;
static int v2_compatibility = 0;
static const int default_api_level = 2;
/* NEW LANGUAGE NOTE:***********************************************
To add a new language, you need to derive your class from
Language and the overload various virtual functions
(more on this as I figure it out)
NEW LANGUAGE NOTE:END ************************************************/
class LUA:public Language {
private:
File *f_begin;
File *f_runtime;
File *f_header;
File *f_wrappers;
File *f_init;
File *f_initbeforefunc;
String *s_luacode; // luacode to be called during init
String *module; //name of the module
Hash *namespaces_hash;
// Parameters for current class. NIL if not parsing class
int have_constructor;
int have_destructor;
String *destructor_action;
String *class_symname;
String *class_fq_symname; // Fully qualified symname - NSpace + '.' + class_symname
String *class_static_nspace;
String *class_parent_nspace;
String *constructor_name;
// Many wrappers forward calls to each other, for example staticmembervariableHandler
// forwards call to variableHandler, which, in turn, makes to call to functionWrapper.
// In order to access information about whether it is static member of class or just
// plain old variable an array current is kept and used as 'log' of call stack.
enum TState {
NO_CPP,
VARIABLE,
MEMBER_FUNC,
CONSTRUCTOR,
DESTRUCTOR,
MEMBER_VAR,
STATIC_FUNC,
STATIC_VAR,
STATIC_CONST, // enums and things like static const int x = 5;
ENUM_CONST, // This is only needed for backward compatibility in C mode
STATES_COUNT
};
bool current[STATES_COUNT];
public:
/* ---------------------------------------------------------------------
* LUA()
*
* Initialize member data
* --------------------------------------------------------------------- */
LUA():
f_begin(0),
f_runtime(0),
f_header(0),
f_wrappers(0),
f_init(0),
f_initbeforefunc(0),
s_luacode(0),
module(0),
have_constructor(0),
have_destructor(0),
destructor_action(0),
class_symname(0),
class_fq_symname(0),
class_static_nspace(0),
constructor_name(0) {
namespaces_hash = NewHash();
for (int i = 0; i < STATES_COUNT; i++)
current[i] = false;
}
~LUA() {
if (namespaces_hash)
Delete(namespaces_hash);
}
bool strToInt(const char *string, int &value) {
long int tmp;
char *p_end = 0;
if (string == 0)
return false;
tmp = strtol(string, &p_end, 10);
if (p_end == 0 || *p_end != 0)
return false;
value = tmp;
return true;
}
/* NEW LANGUAGE NOTE:***********************************************
This is called to initalise the system & read any command line args
most of this is boilerplate code, except the command line args
which depends upon what args your code supports
NEW LANGUAGE NOTE:END *********************************************** */
/* ---------------------------------------------------------------------
* main()
*
* Parse command line options and initializes variables.
* --------------------------------------------------------------------- */
virtual void main(int argc, char *argv[]) {
int api_level = default_api_level; // Default api level
/* Set location of SWIG library */
SWIG_library_directory("lua");
/* Look for certain command line options */
for (int i = 1; i < argc; i++) {
if (argv[i]) {
if (strcmp(argv[i], "-help") == 0) { // usage flags
fputs(usage, stdout);
} else if (strcmp(argv[i], "-nomoduleglobal") == 0) {
nomoduleglobal = 1;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-elua") == 0) {
elua_ltr = 1;
Swig_mark_arg(i);
if (strToInt(argv[i + 1], elua_opt_lvl)) {
Swig_mark_arg(i + 1);
i++;
}
} else if (strcmp(argv[i], "-eluac") == 0) {
eluac_ltr = 1;
Swig_mark_arg(i);
if (strToInt(argv[i + 1], elua_opt_lvl)) {
Swig_mark_arg(i + 1);
i++;
}
} else if (strcmp(argv[i], "-swig3") == 0) {
Swig_mark_arg(i);
api_level = 3;
} else if (strcmp(argv[i], "-squash-bases") == 0) {
Swig_mark_arg(i);
squash_bases = 1;
}
}
}
// Set API-compatibility options
if (api_level <= 2) // Must be compatible with SWIG 2.*
v2_compatibility = 1;
// template for further API breaks
//if(api_level <= 3)
// v3_compatibility = 1;
//if(api_level <= 4)
// v4_compatibility = 1;
/* NEW LANGUAGE NOTE:***********************************************
This is the boilerplate code, setting a few #defines
and which lib directory to use
the SWIG_library_directory() is also boilerplate code
but it always seems to be the first line of code
NEW LANGUAGE NOTE:END *********************************************** */
/* Add a symbol to the parser for conditional compilation */
Preprocessor_define("SWIGLUA 1", 0);
/* Set language-specific configuration file */
SWIG_config_file("lua.swg");
/* Set typemap language */
SWIG_typemap_lang("lua");
/* Enable overloaded methods support */
allow_overloading();
}
/* NEW LANGUAGE NOTE:***********************************************
After calling main, SWIG parses the code to wrap (I believe)
then calls top()
in this is more boilerplate code to set everything up
and a call to Language::top()
which begins the code generations by calling the member fns
after all that is more boilerplate code to close all down
(overall there is virtually nothing here that needs to be edited
just use as is)
NEW LANGUAGE NOTE:END *********************************************** */
/* ---------------------------------------------------------------------
* top()
* --------------------------------------------------------------------- */
virtual int top(Node *n) {
/* Get the module name */
module = Getattr(n, "name");
/* Get the output file name */
String *outfile = Getattr(n, "outfile");
/* Open the output file */
f_begin = NewFile(outfile, "w", SWIG_output_files());
if (!f_begin) {
FileErrorDisplay(outfile);
SWIG_exit(EXIT_FAILURE);
}
f_runtime = NewString("");
f_init = NewString("");
f_header = NewString("");
f_wrappers = NewString("");
f_initbeforefunc = NewString("");
/* Register file targets with the SWIG file handler */
Swig_register_filebyname("header", f_header);
Swig_register_filebyname("wrapper", f_wrappers);
Swig_register_filebyname("begin", f_begin);
Swig_register_filebyname("runtime", f_runtime);
Swig_register_filebyname("init", f_init);
Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
s_luacode = NewString("");
Swig_register_filebyname("luacode", s_luacode);
current[NO_CPP] = true;
/* Standard stuff for the SWIG runtime section */
Swig_banner(f_begin);
Printf(f_runtime, "\n");
Printf(f_runtime, "#define SWIGLUA\n");
emitLuaFlavor(f_runtime);
if (elua_ltr || eluac_ltr)
Printf(f_runtime, "#ifndef MIN_OPT_LEVEL\n" "#define MIN_OPT_LEVEL %d\n" "#endif\n", elua_opt_lvl);
if (nomoduleglobal) {
Printf(f_runtime, "#define SWIG_LUA_NO_MODULE_GLOBAL\n");
} else {
Printf(f_runtime, "#define SWIG_LUA_MODULE_GLOBAL\n");
}
if (squash_bases)
Printf(f_runtime, "#define SWIG_LUA_SQUASH_BASES\n");
// if (NoInclude) {
// Printf(f_runtime, "#define SWIG_NOINCLUDE\n");
// }
Printf(f_runtime, "\n");
//String *init_name = NewStringf("%(title)s_Init", module);
//Printf(f_header, "#define SWIG_init %s\n", init_name);
//Printf(f_header, "#define SWIG_name \"%s\"\n", module);
/* SWIG_import is a special function name for importing within Lua5.1 */
//Printf(f_header, "#define SWIG_import luaopen_%s\n\n", module);
Printf(f_header, "#define SWIG_name \"%s\"\n", module);
Printf(f_header, "#define SWIG_init luaopen_%s\n", module);
Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module);
Printf(f_header, "#define SWIG_LUACODE luaopen_%s_luacode\n", module);
Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
/* %init code inclusion, effectively in the SWIG_init function */
Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n");
Language::top(n);
Printf(f_init, "/* exec Lua code if applicable */\nSWIG_Lua_dostring(L,SWIG_LUACODE);\n");
Printf(f_init, "}\n");
// Done. Close up the module & write to the wrappers
closeNamespaces(f_wrappers);
Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n");
SwigType_emit_type_table(f_runtime, f_wrappers);
/* NEW LANGUAGE NOTE:***********************************************
this basically combines several of the strings together
and then writes it all to a file
NEW LANGUAGE NOTE:END *********************************************** */
Dump(f_runtime, f_begin);
Dump(f_header, f_begin);
Dump(f_wrappers, f_begin);
Dump(f_initbeforefunc, f_begin);
/* for the Lua code it needs to be properly excaped to be added into the C/C++ code */
EscapeCode(s_luacode);
Printf(f_begin, "const char* SWIG_LUACODE=\n \"%s\";\n\n", s_luacode);
Wrapper_pretty_print(f_init, f_begin);
/* Close all of the files */
Delete(s_luacode);
Delete(f_header);
Delete(f_wrappers);
Delete(f_init);
Delete(f_initbeforefunc);
Delete(f_runtime);
Delete(f_begin);
/* Done */
return SWIG_OK;
}
/* ------------------------------------------------------------
* importDirective()
* ------------------------------------------------------------ */
virtual int importDirective(Node *n) {
return Language::importDirective(n);
}
/* ------------------------------------------------------------
* cDeclaration()
* It copies sym:name to lua:name to preserve it's original value
* ------------------------------------------------------------ */
virtual int cDeclaration(Node *n) {
// class 'Language' is messing with symname in a really heavy way.
// Although documentation states that sym:name is a name in
// the target language space, it is not true. sym:name and
// it's derivatives are used in various places, including
// behind-the-scene C code generation. The best way is not to
// touch it at all.
// But we need to know what was the name of function/variable
// etc that user desired, that's why we store correct symname
// as lua:name
String *symname = Getattr(n, "sym:name");
if (symname)
Setattr(n, "lua:name", symname);
return Language::cDeclaration(n);
}
virtual int constructorDeclaration(Node *n) {
Setattr(n, "lua:name", Getattr(n, "sym:name"));
return Language::constructorDeclaration(n);
}
virtual int destructorDeclaration(Node *n) {
Setattr(n, "lua:name", Getattr(n, "sym:name"));
return Language::destructorDeclaration(n);
}
/* NEW LANGUAGE NOTE:***********************************************
This is it!
you get this one right, and most of your work is done
but its going to take soem file to get it working right
quite a bit of this is generally boilerplate code
(or stuff I dont understand)
that which matters will have extra added comments
NEW LANGUAGE NOTE:END *********************************************** */
/* ---------------------------------------------------------------------
* functionWrapper()
*
* Create a function declaration and register it with the interpreter.
* --------------------------------------------------------------------- */
// Helper function. Remembers wrap name
void rememberWrapName(Node *n, String *wrapname) {
Setattr(n, "wrap:name", wrapname);
// If it is getter/setter, then write wrapname under
// wrap:memberset/wrap:memberget accordingly
if (Getattr(n, "memberset"))
Setattr(n, "memberset:wrap:name", wrapname);
if (Getattr(n, "varset"))
Setattr(n, "varset:wrap:name", wrapname);
if (Getattr(n, "memberget"))
Setattr(n, "memberget:wrap:name", wrapname);
if (Getattr(n, "varget"))
Setattr(n, "varget:wrap:name", wrapname);
}
// Add method to the "methods" C array of given namespace/class
void registerMethod(String *nspace_or_class_name, Node *n) {
assert(n);
Hash *nspaceHash = getNamespaceHash(nspace_or_class_name);
String *s_ns_methods_tab = Getattr(nspaceHash, "methods");
String *wname = Getattr(n, "wrap:name");
String *iname = Getattr(n, "sym:name");
String *target_name = Getattr(n, "lua:name");
if (elua_ltr || eluac_ltr)
Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", iname, "\")", ", LFUNCVAL(", wname, ")", "},\n", NIL);
else
Printv(s_ns_methods_tab, tab4, "{ \"", target_name, "\", ", wname, "},\n", NIL);
}
// Helper for functionWrapper - determines whether we should
// register method in the appropriate class/namespace/module
// table or not.
// (not => it is variable wrapper or something similar)
bool functionWrapperRegisterNow() const {
if (current[VARIABLE])
return false;
return (current[NO_CPP] || current[STATIC_FUNC]);
}
virtual int functionWrapper(Node *n) {
REPORT("functionWrapper", n);
String *name = Getattr(n, "name");
String *iname = Getattr(n, "sym:name");
String *target_name = Getattr(n, "lua:name");
assert(target_name);
SwigType *d = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
Parm *p;
String *tm;
int i;
//Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current);
String *overname = 0;
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!luaAddSymbol(target_name, n)) {
return SWIG_ERROR;
}
}
/* NEW LANGUAGE NOTE:***********************************************
the wrapper object holds all the wrappering code
we need to add a couple of local variables
NEW LANGUAGE NOTE:END *********************************************** */
Wrapper *f = NewWrapper();
Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = 0");
String *wname = symnameWrapper(iname);
if (overname) {
Append(wname, overname);
}
if (current[CONSTRUCTOR]) {
if (constructor_name != 0)
Delete(constructor_name);
constructor_name = Copy(wname);
}
/* NEW LANGUAGE NOTE:***********************************************
the format of a lua fn is:
static int wrap_XXX(lua_State* L){...}
this line adds this into the wrappering code
NEW LANGUAGE NOTE:END *********************************************** */
Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
/* NEW LANGUAGE NOTE:***********************************************
this prints the list of args, eg for a C fn
int gcd(int x,int y);
it will print
int arg1;
int arg2;
NEW LANGUAGE NOTE:END *********************************************** */
/* Write code to extract function parameters. */
emit_parameter_variables(l, f);
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
/* Get number of required and total arguments */
int num_arguments = emit_num_arguments(l);
int num_required = emit_num_required(l);
int varargs = emit_isvarargs(l);
// Check if we have to ignore arguments that are passed by LUA.
// Needed for unary minus, where lua passes two arguments and
// we have to ignore the second.
int args_to_ignore = 0;
if (Getattr(n, "lua:ignore_args")) {
args_to_ignore = GetInt(n, "lua:ignore_args");
}
/* NEW LANGUAGE NOTE:***********************************************
from here on in, it gets rather hairy
this is the code to convert from the scripting language to C/C++
some of the stuff will refer to the typemaps code written in your swig file
(lua.swg), and some is done in the code here
I suppose you could do all the conversion on C, but it would be a nightmare to do
NEW LANGUAGE NOTE:END *********************************************** */
/* Generate code for argument marshalling */
// String *description = NewString("");
/* NEW LANGUAGE NOTE:***********************************************
argument_check is a new feature I added to check types of arguments:
eg for int gcd(int,int)
I want to check that arg1 & arg2 really are integers
NEW LANGUAGE NOTE:END *********************************************** */
String *argument_check = NewString("");
String *argument_parse = NewString("");
String *checkfn = NULL;
char source[64];
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);
for (i = 0, p = l; i < num_arguments; i++) {
while (checkAttribute(p, "tmap:in:numinputs", "0")) {
p = Getattr(p, "tmap:in:next");
}
SwigType *pt = Getattr(p, "type");
String *ln = Getattr(p, "lname");
/* Look for an input typemap */
sprintf(source, "%d", i + 1);
if ((tm = Getattr(p, "tmap:in"))) {
Replaceall(tm, "$source", source);
Replaceall(tm, "$target", ln);
Replaceall(tm, "$input", source);
Setattr(p, "emit:input", source);
if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
} else {
Replaceall(tm, "$disown", "0");
}
/* NEW LANGUAGE NOTE:***********************************************
look for a 'checkfn' typemap
this an additional parameter added to the in typemap
if found the type will be tested for
this will result in code either in the
argument_check or argument_parse string
NEW LANGUAGE NOTE:END *********************************************** */
if ((checkfn = Getattr(p, "tmap:in:checkfn"))) {
if (i < num_required) {
Printf(argument_check, "if(!%s(L,%s))", checkfn, source);
} else {
Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source);
}
Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", Swig_name_str(n), source, SwigType_str(pt, 0));
}
/* NEW LANGUAGE NOTE:***********************************************
lua states the number of arguments passed to a function using the fn
lua_gettop()
we can use this to deal with default arguments
NEW LANGUAGE NOTE:END *********************************************** */
if (i < num_required) {
Printf(argument_parse, "%s\n", tm);
} else {
Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm);
}
p = Getattr(p, "tmap:in:next");
continue;
} else {
/* NEW LANGUAGE NOTE:***********************************************
// why is this code not called when I dont have a typemap?
// instead of giving a warning, no code is generated
NEW LANGUAGE NOTE:END *********************************************** */
Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
break;
}
}
// add all argcheck code
Printv(f->code, argument_check, argument_parse, NIL);
/* Check for trailing varargs */
if (varargs) {
if (p && (tm = Getattr(p, "tmap:in"))) {
Replaceall(tm, "$input", "varargs");
Printv(f->code, tm, "\n", NIL);
}
}
/* Insert constraint checking code */
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:check"))) {
Replaceall(tm, "$target", Getattr(p, "lname"));
Printv(f->code, tm, "\n", NIL);
p = Getattr(p, "tmap:check:next");
} else {
p = nextSibling(p);
}
}
/* Insert cleanup code */
String *cleanup = NewString("");
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:freearg"))) {
Replaceall(tm, "$source", Getattr(p, "lname"));
Printv(cleanup, tm, "\n", NIL);
p = Getattr(p, "tmap:freearg:next");
} else {
p = nextSibling(p);
}
}
/* Insert argument output code */
String *outarg = NewString("");
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:argout"))) {
// // managing the number of returning variables
// if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){
// int i=GetInt(p,"tmap:argout:numoutputs");
// printf("got argout:numoutputs of %d\n",i);
// returnval+=GetInt(p,"tmap:argout:numoutputs");
// }
// else returnval++;
Replaceall(tm, "$source", Getattr(p, "lname"));
Replaceall(tm, "$target", Swig_cresult_name());
Replaceall(tm, "$arg", Getattr(p, "emit:input"));
Replaceall(tm, "$input", Getattr(p, "emit:input"));
Printv(outarg, tm, "\n", NIL);
p = Getattr(p, "tmap:argout:next");
} else {
p = nextSibling(p);
}
}
// Remember C name of the wrapping function
rememberWrapName(n, wname);
/* Emit the function call */
String *actioncode = emit_action(n);
/* NEW LANGUAGE NOTE:***********************************************
FIXME:
returns 1 if there is a void return type
this is because there is a typemap for void
NEW LANGUAGE NOTE:END *********************************************** */
// Return value if necessary
if ((tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode))) {
// managing the number of returning variables
// if (numoutputs=Getattr(tm,"numoutputs")){
// int i=GetInt(tm,"numoutputs");
// printf("return numoutputs %d\n",i);
// returnval+=GetInt(tm,"numoutputs");
// }
// else returnval++;
Replaceall(tm, "$source", Swig_cresult_name());
if (GetFlag(n, "feature:new")) {
Replaceall(tm, "$owner", "1");
} else {
Replaceall(tm, "$owner", "0");
}
Printf(f->code, "%s\n", tm);
// returnval++;
} else {
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);
}
emit_return_variable(n, d, f);
/* Output argument output code */
Printv(f->code, outarg, NIL);
/* Output cleanup code */
Printv(f->code, cleanup, NIL);
/* Look to see if there is any newfree cleanup code */
if (GetFlag(n, "feature:new")) {
if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) {
Replaceall(tm, "$source", Swig_cresult_name());
Printf(f->code, "%s\n", tm);
}
}
/* See if there is any return cleanup code */
if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) {
Replaceall(tm, "$source", Swig_cresult_name());
Printf(f->code, "%s\n", tm);
}
/* Close the function */
Printv(f->code, "return SWIG_arg;\n", NIL);
// add the failure cleanup code:
Printv(f->code, "\nif(0) SWIG_fail;\n", NIL);
Printv(f->code, "\nfail:\n", NIL);
Printv(f->code, "$cleanup", "lua_error(L);\n", NIL);
Printv(f->code, "return SWIG_arg;\n", NIL);
Printf(f->code, "}\n");
/* Substitute the cleanup code */
Replaceall(f->code, "$cleanup", cleanup);
/* Substitute the function name */
Replaceall(f->code, "$symname", iname);
Replaceall(f->code, "$result", Swig_cresult_name());
/* Dump the function out */
/* in Lua we will not emit the destructor as a wrappered function,
Lua will automatically call the destructor when the object is free'd
However: you cannot just skip this function as it will not emit
any custom destructor (using %extend), as you need to call emit_action()
Therefore we go though the whole function,
but do not write the code into the wrapper
*/
if (!current[DESTRUCTOR]) {
Wrapper_print(f, f_wrappers);
}
/* NEW LANGUAGE NOTE:***********************************************
register the function in SWIG
different language mappings seem to use different ideas
NEW LANGUAGE NOTE:END *********************************************** */
/* Now register the function with the interpreter. */
int result = SWIG_OK;
if (!Getattr(n, "sym:overloaded")) {
if (functionWrapperRegisterNow()) { // emit normal fns & static fns
registerMethod(luaCurrentSymbolNSpace(), n);
}
} else {
if (!Getattr(n, "sym:nextSibling")) {
result = dispatchFunction(n);
}
}
Delete(argument_check);
Delete(argument_parse);
Delete(cleanup);
Delete(outarg);
// Delete(description);
DelWrapper(f);
return result;
}
/* ------------------------------------------------------------
* dispatchFunction()
*
* Emit overloading dispatch function
* ------------------------------------------------------------ */
/* NEW LANGUAGE NOTE:***********************************************
This is an extra function used for overloading of functions
it checks the args & then calls the relevant fn
nost of the real work in again typemaps:
look for %typecheck(SWIG_TYPECHECK_*) in the .swg file
NEW LANGUAGE NOTE:END *********************************************** */
int dispatchFunction(Node *n) {
//REPORT("dispatchFunction", n);
/* Last node in overloaded chain */
int maxargs;
String *tmp = NewString("");
String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs);
/* Generate a dispatch wrapper for all overloaded functions */
Wrapper *f = NewWrapper();
String *symname = Getattr(n, "sym:name");
String *target_name = Getattr(n, "lua:name");
assert(target_name);
String *wname = symnameWrapper(symname);
//Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs);
if (!luaAddSymbol(target_name, n)) {
return SWIG_ERROR;
}
Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL);
Wrapper_add_local(f, "argc", "int argc");
Printf(tmp, "int argv[%d]={1", maxargs + 1);
for (int i = 1; i <= maxargs; i++) {
Printf(tmp, ",%d", i + 1);
}
Printf(tmp, "}");
Wrapper_add_local(f, "argv", tmp);
Printf(f->code, "argc = lua_gettop(L);\n");
Replaceall(dispatch, "$args", "self,args");
Printv(f->code, dispatch, "\n", NIL);
Node *sibl = n;
while (Getattr(sibl, "sym:previousSibling"))
sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up
String *protoTypes = NewString("");
do {
String *fulldecl = Swig_name_decl(sibl);
Printf(protoTypes, "\n\" %s\\n\"", fulldecl);
Delete(fulldecl);
} while ((sibl = Getattr(sibl, "sym:nextSibling")));
Printf(f->code, "SWIG_Lua_pusherrstring(L,\"Wrong arguments for overloaded function '%s'\\n\"\n"
"\" Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes);
Delete(protoTypes);
Printf(f->code, "lua_error(L);return 0;\n");
Printv(f->code, "}\n", NIL);
Wrapper_print(f, f_wrappers);
// Remember C name of the wrapping function
rememberWrapName(n, wname);
if (functionWrapperRegisterNow()) { // emit normal fns & static fns
registerMethod(luaCurrentSymbolNSpace(), n);
}
if (current[CONSTRUCTOR]) {
if (constructor_name != 0)
Delete(constructor_name);
constructor_name = Copy(wname);
}
DelWrapper(f);
Delete(dispatch);
Delete(tmp);
return SWIG_OK;
}
/* ------------------------------------------------------------
* Add variable to the "attributes" (or "get"/"set" in
* case of elua_ltr) C arrays of given namespace or class
* ------------------------------------------------------------ */
void registerVariable(String *nspace_or_class_name, Node *n, const char *getAttrName, const char *setAttrName) {
String *unassignable = NewString("SWIG_Lua_set_immutable");
String *getName = Getattr(n, getAttrName);
String *setName = Getattr(n, setAttrName);
if (setName == 0 || GetFlag(n, "feature:immutable")) {
setName = unassignable;
}
Hash *nspaceHash = getNamespaceHash(nspace_or_class_name);
String *s_ns_methods_tab = Getattr(nspaceHash, "methods");
String *s_ns_var_tab = Getattr(nspaceHash, "attributes");
String *target_name = Getattr(n, "lua:name");
if (elua_ltr) {
String *s_ns_dot_get = Getattr(nspaceHash, "get");
String *s_ns_dot_set = Getattr(nspaceHash, "set");
Printf(s_ns_dot_get, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, getName);
Printf(s_ns_dot_set, "%s{LSTRKEY(\"%s\"), LFUNCVAL(%s)},\n", tab4, target_name, setName);
} else if (eluac_ltr) {
Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_get", "\")", ", LFUNCVAL(", getName, ")", "},\n", NIL);
Printv(s_ns_methods_tab, tab4, "{LSTRKEY(\"", target_name, "_set", "\")", ", LFUNCVAL(", setName, ")", "},\n", NIL);
} else {
Printf(s_ns_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, target_name, getName, setName);
}
}
/* ------------------------------------------------------------
* variableWrapper()
* ------------------------------------------------------------ */
virtual int variableWrapper(Node *n) {
/* NEW LANGUAGE NOTE:***********************************************
Language::variableWrapper(n) will generate two wrapper fns
Foo_get & Foo_set by calling functionWrapper()
so we will just add these into the variable lists
ideally we should not have registered these as functions,
only WRT this variable will look into this later.
NEW LANGUAGE NOTE:END *********************************************** */
// REPORT("variableWrapper", n);
String *target_name = Getattr(n, "lua:name");
assert(target_name);
current[VARIABLE] = true;
// let SWIG generate the wrappers
int result = Language::variableWrapper(n);
registerVariable(luaCurrentSymbolNSpace(), n, "varget:wrap:name", "varset:wrap:name");
current[VARIABLE] = false;
return result;
}
/* ------------------------------------------------------------
* Add constant to appropriate C array. constantRecord is an array record.
* Actually, in current implementation it is resolved consttab typemap
* ------------------------------------------------------------ */
void registerConstant(String *nspace, String *constantRecord) {
Hash *nspaceHash = getNamespaceHash(nspace);
String *s_const_tab = 0;
if (eluac_ltr || elua_ltr)
// In elua everything goes to "methods" tab
s_const_tab = Getattr(nspaceHash, "methods");
else
s_const_tab = Getattr(nspaceHash, "constants");
assert(s_const_tab);
Printf(s_const_tab, " %s,\n", constantRecord);
if ((eluac_ltr || elua_ltr) && v2_compatibility) {
s_const_tab = Getattr(nspaceHash, "constants");
assert(s_const_tab);
Printf(s_const_tab, " %s,\n", constantRecord);
}
}
/* ------------------------------------------------------------
* constantWrapper()
* ------------------------------------------------------------ */
virtual int constantWrapper(Node *n) {
REPORT("constantWrapper", n);
String *name = Getattr(n, "name");
String *iname = Getattr(n, "sym:name");
String *target_name = Getattr(n, "lua:name");
if (target_name == 0)
target_name = iname;
String *nsname = Copy(iname);
SwigType *type = Getattr(n, "type");
String *rawval = Getattr(n, "rawval");
String *value = rawval ? rawval : Getattr(n, "value");
String *tm;
String *target_name_v2 = 0;
String *tm_v2 = 0;
String *iname_v2 = 0;
Node *n_v2 = 0;
if (!luaAddSymbol(target_name, n))
return SWIG_ERROR;
Swig_save("lua_constantMember", n, "sym:name", NIL);
Setattr(n, "sym:name", target_name);
/* Special hook for member pointer */
if (SwigType_type(type) == T_MPOINTER) {
String *wname = symnameWrapper(iname);
Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value);
value = Char(wname);
}
if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
//Printf(stdout, "tm v1: %s\n", tm); // TODO:REMOVE