-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathluna_gen.lua
1790 lines (1679 loc) · 60.7 KB
/
luna_gen.lua
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
script_path=string.sub(arg[0],1,-14)
package.path=script_path.."/?.lua;"..package.path
require('mylib')
source_file_name,source_path=os.processFileName(arg[1])
if source_path=='' then source_path='.' end
if math.mod ==nil then
math.mod=function (a,b) return a%b end
end
if _VERSION=='Lua 5.2' then
print('lua 5.2 is not yet supported!')
end
do -- user configurations : all these can be changed in input file or from command line argument.
verbosecpp=true -- easy for debugging cpp compilation error
verbose=false
gen_lua={}
gen_lua.supportedClassProperties={'^ifdef$','^ifndef$','^isLuaInheritable$','^isExtendableFromLua$',
'^headerFile$','^decl$','^if_$', '^enums$','^inheritsFrom$', '^name$','^className$','^ctors$','^wrapperCode$',
'^globalWrapperCode', '^staticMemberFunctions$', '^memberFunctionsFromFile$', '^memberFunctions$',
'^read_properties$','^write_properties$','^customFunctionsToRegister$', '^properties$',}
-- you can use luaName instead of name
-- you can use cppName instead of className
gen_lua.classProperty_name_translation={
luaName="name",
luaname="name",
cppName='className',
cppname='className',
ctor='ctors',
constructor='ctors',
constructors='ctors',
superClass='inheritsFrom',
super='inheritsFrom',
parentClass='inheritsFrom',
}
gen_lua.number_types={'int', 'double', 'float','long', 'short'}
gen_lua.enum_types={}
gen_lua.boolean_types={'bool'}
gen_lua.string_types={'const%s+char%s*%*', 'std%s*::%s*string', 'TString'} -- string types has to support static conversion to const char*, and construction from const char*.
gen_lua.string_to_cstr={'@' , '@.c_str()', '@.ptr()'}
gen_lua.string_from_cstr={'@' , 'std::string(@)', 'TString(@)'}
gen_lua.auto_rename={{'__eq','operator%s*=='},{'__call', 'operator%s*%[%s*%]'},{'__le', 'operator%s*<='},{'__lt', 'operator%s*<'},{'rsub', 'operator%s*-='},{'rmod', 'operator%s*%%='},{'radd', 'operator%s*+='},{'rmult', 'operator%s*%*='}, {'rdiv', 'operator%s*/='},{'assign', 'operator%s*='},{'__call','operator%s*%(%s*%)'},{'__div','operator%s*/'},{'__mul','operator%s*%*'},{'__add','operator%s*+'}, {'__sub','operator%s*-'},{'__mod', 'operator%s*%%'},} -- operator()
gen_lua.modifiers={'const', '%*', '&','inline','virtual'}
gen_lua.single_letter_modifiers={'%*', '&'}
gen_lua.enable_type_checking=true -- even with this option turned off, some type checking that don't affect computation time is still turned on.
gen_lua.generate_debug_printf=false -- for debugging luna_gen.lua
gen_lua.catch_cpp_exception=true -- catches std::exception(...)
gen_lua.catch_string='\t} catch(std::exception& e) { luaL_error( L,e.what()); }'
gen_lua.catch_string=[[
}
catch(std::exception& e) { luaL_error( L,e.what()); }
catch(...) { luaL_error( L,"unknown_error");}
]]
gen_lua.no_unmodified_overwriting=false -- set true if you don't want to overwrite the output file when it's unchanged. Setting this true can conflict with make's dependency checking.
gen_lua.use_profiler=false -- uses performance profiler. See test_profiler sample.
if os.isWindows() then
gen_lua.no_unmodified_overwriting=true -- this works better with windows visual studio
end
end
-- How to read code.
-- Parsing:
-- function buildDefinitionDB(...)
-- Main: at the end of this file
do -- system conf : will be generated by the system
gen_lua.type_error_msg='type "gen_lua.type_names" to see all registered types'
gen_lua.cpp_contents={}
gen_lua.complex_type_names={} -- in pattern form
gen_lua.luna_types={} -- will be obtained from build definitionsDB.
gen_lua.type_names={'void'} -- in normalized form (see normalizeClassName below)
gen_lua.usedHashValue={}
gen_lua.getNameSpace={}
gen_lua.defNameSpaceCode=''
gen_lua.definitionDBbuilt=false
gen_lua.declarationWritten=false
gen_lua.writeHeaderCounter=1
gen_lua.moduleUniqueId=1
end
-- TODO:
-- overloading doesn't work when there are both staticMemberFunctions and memberFunctions having the same name.
--
-- NOTE:
-- Please use editors that support source-code folding based on indentation. (In my case, vim).
-- Otherwise, this code would be very difficult to read.
-- default options
do -- utility functions
function processNamespaces(parent, parentName)
local str=""
if parent then
for k, v in pairs(parent) do
if type(v)=='table' then
if parentName~="" then
str=str..'\n'.. [[
if ]]..parentName..k..[[==nil then
]]..parentName..k..[[={}
end
]]
end
end
end
for k, v in pairs(parent) do
if type(v)=='table' then
for i,cname in ipairs(v) do
gen_lua.getNameSpace[normalizeClassName(cname)]=parentName..k
end
end
end
for k, v in pairs(parent) do
if type(v)=='table' then
str=str..'\n'..processNamespaces(v, parentName..k..'.')
end
end
end
return str
end
function luacodeInCquote(luacode)
luacode=string.gsub(luacode, "\n","\\n")
luacode=string.gsub(luacode, "\"","\\\"")
return '"'..luacode..'"'
end
function filter(check, valtrue, valfalse)
if check then return valtrue end
return valfalse
end
function codeDostring(luaCode)
return " luna_dostring(L,"..luacodeInCquote(luaCode)..");" -- luaL_dostring followed by pcall error checking
end
function codeRequireMylib(additionalLuaCode)
return "luna_dostring(L, "..luacodeInCquote([[
package.path=package.path..";]]..script_path..[[/?.lua"
require('mylib')
]]..(additionalLuaCode or "") ) -- closing luacodeInCquote
..");\n" -- closing luaL_dostring
end
function writeLaunchLuaDebugger()
write(codeRequireMylib('dbg.console()'))
end
function loadDefinitionDB(filename)
local fcn,msg=loadstring('return '..util.readFile(filename))
if not fcn then lgerror(msg) end
local db=fcn()
array.concat(gen_lua.cpp_contents, db.cpp_contents)
array.concat(gen_lua.complex_type_names, db.complex_type_names)
array.concat(gen_lua.type_names, db.type_names)
table.mergeInPlace(gen_lua.luna_types, db.luna_types)
table.mergeInPlace(gen_lua.usedHashValue, db.usedHashValue)
if(db.autoConversion_rectified) then
if not gen_lua.autoConversion_rectified then
gen_lua.autoConversion_rectified={}
end
table.mergeInPlace(gen_lua.autoConversion_rectified, db.autoConversion_rectified)
end
array.concat(gen_lua.getNameSpace, db.getNameSpace)
--array.concat(gen_lua.getNameSpaceCode, db.getNameSpaceCode)
gen_lua.moduleUniqueId=gen_lua.moduleUniqueId+db.moduleUniqueId+1
gen_lua.writeHeaderCounter=gen_lua.writeHeaderCounter+db.writeHeaderCounter+1
for i,v in ipairs(db.number_types) do
array.pushBackIfNotExist(gen_lua.number_types,v)
end
for i,v in ipairs(db.enum_types) do
array.pushBackIfNotExist(gen_lua.enum_types,v)
end
for i,v in ipairs(db.boolean_types) do
array.pushBackIfNotExist(gen_lua.boolean_types,v)
end
end
function writeDefinitionDBtoFile(filename)
local db={}
db.cpp_contents=gen_lua.cpp_contents
db.complex_type_names=gen_lua.complex_type_names
db.luna_types={}
-- copy properties that are absolutely necessary
for k,v in pairs(gen_lua.luna_types) do
local tbl={}
tbl.external=true
tbl.className=v.className
tbl.isModule=v.isModule
tbl.uniqueID=v.uniqueID
tbl.uniqueLuaClassname=v.uniqueLuaClassname
tbl.uppermostParent={
className=v.uppermostParent.className,
uniqueID=v.uppermostParent.uniqueID,
}
db.luna_types[k]=tbl
end
db.type_names=gen_lua.type_names
db.usedHashValue=gen_lua.usedHashValue
db.getNameSpace=gen_lua.getNameSpace
db.getNameSpaceCode=gen_lua.getNameSpaceCode
db.writeHeaderCounter= gen_lua.writeHeaderCounter
db.moduleUniqueId= gen_lua.moduleUniqueId
db.number_types=gen_lua.number_types
db.enum_types=gen_lua.enum_types
db.boolean_types=gen_lua.boolean_types
db.autoConversion_rectified=gen_lua.autoConversion_rectified
local str=table.tostring(db)
print('generating '..filename)
util.writeFile(filename, str)
end
function writeIncludeBlock(not_include_luna)
write([[
#include <stdio.h>
#include <string.h>
#include <string>
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
//#include "luadebug.h"
}
]])
if not not_include_luna then
write('#include "luna.h"')
end
if gen_lua.use_profiler then
write([[
#include "QPerformanceTimer.h"
]])
end
end
function addOverloadDefinition(retType, defaultRetVal, overloaded)
-- overloaded function body definition: redirect function calls to the relevant overloaded functions
for k,v in pairs(overloaded) do
local vv=v[1]
addLine(' static '..retType..' _bind_'..k..'(lua_State *L)\n {')
for i,vv in ipairs(v) do
addLine(' if (_lg_typecheck_'..vv.luaname..'(L)) return _bind_'..vv.luaname..'(L);')
end
local msg='\\n'
for i,vv in ipairs(v) do
msg=msg..'('..argsToString(vv.args)..')\\n'
end
addLine(' luaL_error(L, "'..k..' ( cannot find overloads:)'..msg..'");\n')
addLine(' return '..defaultRetVal..';')
addLine(' }')
end
end
function tokenizeArg(arg, tokens) -- input: const char* a -> output: const, char, *, a
local ttokens= string.tokenize(arg, '%s')
for j,m in ipairs(tokens) do
local tokens={}
for i,v in ipairs(ttokens) do
array.concat(tokens, string.tokenize2(v, m, string.gsub(m,'%%','')))
end
ttokens=tokens
end
return ttokens
end
function genInterfaceName(luaclass)
if not luaclass.isModule then
return 'LunaTraits<'..normalizedClassNameToClassName(luaclass.className)..' >'
else
return 'luna__interface_'..string.gsub(luaclass.uniqueLuaClassname,'@','_1_')
end
end
function Hash(str)
local n=#str
local h=0
for i=1,n do
h=31*h+string.byte(str,i)
h=math.mod(h,100000000+i)
end
return h
end
function lgerror(...)
print("Error!",...)
print('\nCallstack:')
dbg.callstack()
print('\nEntering debugging console (typically typing c, c2, c3, c4, ... reveals more details)')
dbg.console()
end
function addReturnType(vv, cppname)
if vv.if_ then
addLine('#if '..vv.if_)
end
local catch=gen_lua.catch_cpp_exception
if vv.returnType.c=='void' then
if catch then addLine('\ttry {') end
addLine('\t'..cppname..'('..parsedNames(vv.args)..');')
if catch then addLine(gen_lua.catch_string) end
addLine(' return 0;')
else
if isLunaType(vv.returnType) then
local ia=vv.returnType
local cp=findLunaClassProperty(ia)
local cppclass_name=normalizedClassNameToClassName(cp.className)
local cpp_parent_classname=normalizedClassNameToClassName(cp.uppermostParent.className)
local cppinterface_name=genInterfaceName(cp)
local t=ia.t
local ii=string.find(ia.t,'%*')
if ii then
-- pointer type:
local adopt=vv.adopt or false
if catch then addLine('\ttry {') end
addLine('\t'..vv.returnType.t..' ret='..cppname..'('..parsedNames(vv.args)..');')
addLine(' if (ret==NULL) lua_pushnil(L); else ')
addLine(' Luna<'..cpp_parent_classname..' >::push(L,('..cpp_parent_classname..' *)ret,'..tostring(adopt)..',"'..cp.uniqueLuaClassname..'");')
if catch then addLine(gen_lua.catch_string) end
else
ii=string.find(ia.t,'%&')
if ii then
local adopt=false
-- reference type:
if catch then addLine('\ttry {') end
addLine('\t'..vv.returnType.t..' ret='..cppname..'('..parsedNames(vv.args)..');')
addLine(' Luna<'..cpp_parent_classname..' >::push(L,&ret,'..tostring(adopt)..',"'..cp.uniqueLuaClassname..'");')
if catch then addLine(gen_lua.catch_string) end
else
local adopt=true
-- value type : copy constructor
if catch then addLine('\ttry {') end
local inputToCtor=cppname..'('..parsedNames(vv.args)..')'
if inputToCtor=='self.operator-()' then
inputToCtor='-self'
end
addLine('\t::'..vv.returnType.t..'* ret=new ::'..vv.returnType.t..'('..inputToCtor..');')
addLine(' Luna< ::'..cpp_parent_classname..' >::push(L,ret,'..tostring(adopt)..',"'..cp.uniqueLuaClassname..'");')
if catch then addLine(gen_lua.catch_string) end
end
end
addLine(' return 1;')
elseif isNumberType(vv.returnType) then
if catch then addLine('\ttry {') end
addLine('\t'..vv.returnType.t..' ret='..cppname..'('..parsedNames(vv.args)..');')
addLine(' lua_pushnumber(L, ret);')
if catch then addLine(gen_lua.catch_string) end
addLine(' return 1;')
elseif isStringType(vv.returnType) then
if catch then addLine('\ttry {') end
addLine('\t'..vv.returnType.t..' ret='..cppname..'('..parsedNames(vv.args)..');')
for i,v in ipairs(gen_lua.string_types) do
if select(1,string.find(vv.returnType.c, v))~=nil then
addLine(' lua_pushstring(L, '..string.gsub(gen_lua.string_to_cstr[i],'@','ret')..');')
break
end
end
if catch then addLine(gen_lua.catch_string) end
addLine(' return 1;')
elseif isBooleanType(vv.returnType) then
if catch then addLine('\ttry {') end
addLine('\t'..vv.returnType.t..' ret='..cppname..'('..parsedNames(vv.args)..');')
addLine(' lua_pushboolean(L, ret);')
if catch then addLine(gen_lua.catch_string) end
addLine(' return 1;')
elseif vv.returnType.t=='void' then
addLine(' return 0;')
else
lgerror('unknown return type '..vv.returnType.t..':'..table.tostring(vv))
end
end
if vv.if_ then
addLine('#else')
addLine(' return 0;')
addLine('#endif')
end
addLine(' }')
end
function addLine(line)
if verbose==true then
print(':: '..line)
end
if verbosecpp then
local linen = debug.getinfo(2).currentline
line=string.gsub(line, '\t', ' ')
local lines=string.lines(line)
local lline=lines[#lines]
if #lline<61 then
lines[#lines]=lline..string.rep(' ',61-#lline)
end
line=table.concat(lines, '\n')
array.pushBack(gen_lua.cpp_contents, line.." // "..linen)
else
array.pushBack(gen_lua.cpp_contents, line)
end
end
function isAutoConversionType(ia)
local a=gen_lua.autoConversion_rectified
if a and a[normalizeClassName(ia.c)] then
return true
end
return false
end
function autoConversionType(ia)
local a=gen_lua.autoConversion_rectified
assert(a)
local convert_to= a[normalizeClassName(ia.c)]
return convert_to
end
function isLunaType(ia)
if ia.t==nil then lgerror('Error! isLunaType') end
return findLunaClassProperty(ia)~=nil
end
function findLunaClassProperty(ia)
local str=ia.c
if( not str) then lgerror('findLunaClassProperty', ia.t, ia.n, ia.c) end
return gen_lua.luna_types[normalizeClassName(str)]
end
function isNumberType(ia)
if ia.t==nil then lgerror('Error! isNumberType') end
if string.isMatched(ia.t, gen_lua.number_types) then
return true
end
if string.isMatched(ia.t, gen_lua.enum_types) then
return true
end
return false
end
function isEnumType(ia)
if ia.t==nil then lgerror('Error! isNumberType') end
if string.isMatched(ia.t, gen_lua.enum_types) then
return true
end
return false
end
function isBooleanType(ia)
if ia.t==nil then lgerror('Error! isBooleanType') end
if string.isMatched(ia.t, gen_lua.boolean_types) then
return true
end
return false
end
function isStringType(ia)
if ia.t==nil then lgerror('Error! isStringType') end
if string.isMatched(ia.t, gen_lua.string_types) then
return true
end
return false
end
function parsedNames(arg)
local str=''
for i,v in ipairs(arg) do
str=str..', '..v.n
end
return string.sub(str,2)
end
function tagOverloadedFunctions(ftns)
local nameTable={}
for i, ftn in ipairs(ftns) do
if nameTable[ftn.luaname]==nil then
nameTable[ftn.luaname]={ftn}
else
array.pushBack(nameTable[ftn.luaname], ftn)
end
end
for k, nt in pairs(nameTable) do
if #nt>1 then
local orig_luaname
for i,ftn in ipairs(nt) do
ftn.overloaded=true
orig_luaname=ftn.luaname
ftn.luaname=ftn.luaname..'_overload_'..tostring(i)
end
if ftns.overloaded==nil then
ftns.overloaded={}
end
ftns.overloaded[orig_luaname]= nt
end
end
end
function parseMemberFunction (fn)
local tbl
if type(fn)=='table' then
tbl=parseMemberFunction(fn[1])
for k,v in pairs(fn) do
if k~=1 then
if k=='rename' then
tbl.luaname=v
else
tbl[k]=v -- pass through other options
end
end
end
return tbl
else
assert(type(fn)=='string')
local cppname_orig
for i,vv in ipairs(gen_lua.auto_rename) do
local k=vv[1]
local v=vv[2]
local s,e=string.find(fn, v)
if s then
cppname_orig=string.sub(fn, s,e)
fn=string.gsub(fn,v,k)
end
end
if select(1,string.find(fn,'=')) then
lgerror(fn..'\ndefault parameter is not allowed. Declare two functions instead. E.g. (X) void a(int a=3) \n(O) void a(int a)\n void a() ')
end
local s,e,c=string.find(fn, '%(')
if not s then lgerror('unknown function definition format', fn) end
local part1=string.sub(fn,1,s-1)
local s2,e2=string.find(fn, '%)')
if not s2 or s2<s then lgerror('unknown function definition format', fn) end
local part2=string.sub(fn, e,s2)
part1=string.trimRight(part1)
local a,b,sepStr=os.rightTokenize(part1, '[%s&%*]', true)
if sepStr=='&' and string.sub(a, -9)=='operator&' then
a=string.sub(a, 1,-10)
b='operator&'..b
end
local ccc=string.find(b,'::')
local luaname=b
if ccc then
luaname=string.sub(b, ccc+2) -- discard cpp namespace name
end
local input_args=parseArg(part2)
if #input_args==1 and input_args[1].t=='void' then
input_args[1]=nil
end
tbl={returnType= parseArg("("..string.trimSpaces(a)..")")[1], cppname=cppname_orig or b, luaname=luaname, args=input_args}
end
return tbl
end
function argsToString(args)
local str=""
for i=1,#args do
local arg=args[i]
str=str..arg.t..' '..arg.n..','
end
return str
end
function addParsedArg(vv, args)
if gen_lua.enable_type_checking and not vv.overloaded then
addLine(' if (!_lg_typecheck_'..vv.luaname..'(L)) { char msg[]="luna typecheck failed:\\n '..vv.luaname..'('..argsToString(args)..')"; puts(msg); luna_printStack(L); luaL_error(L, msg); }\n')
end
if vv.if_ then
addLine('#if '..vv.if_)
end
for i,ia in ipairs(args) do
if isLunaType(ia) then
--local t=string.gsub(ia.t,'%&','') -- remove reference
local t=ia.t
local cp=findLunaClassProperty(ia)
local cppclass_name=normalizedClassNameToClassName(cp.className)
local cppinterface_name=genInterfaceName(cp)
local cpp_parent_classname=normalizedClassNameToClassName(cp.uppermostParent.className)
local t_modifiers=string.gsub(t, normalizedClassNameToPattern(normalizeClassName(ia.c)), '')
if select(1,string.find(t_modifiers,'*')) then
addLine(' '..t..' '..ia.n..'=static_cast<'..cppclass_name..' *>(Luna<'..cpp_parent_classname..' >::check(L,'..i..'));')
else
local ii=string.find(ia.t,'%&')
if not ii then t=t..'&' end -- add reference
addLine(' '..t..' '..ia.n..'=static_cast<'..cppclass_name..' &>(*Luna<'..cpp_parent_classname..' >::check(L,'..i..'));')
end
elseif isStringType(ia) then
addLine(' '..ia.t..' '..ia.n..'=('..ia.t..')lua_tostring(L,'..i..');')
elseif isNumberType(ia) then
if isEnumType(ia) then
addLine(' '..ia.t..' '..ia.n..'=('..ia.t..')(int)lua_tonumber(L,'..i..');')
else
addLine(' '..ia.t..' '..ia.n..'=('..ia.t..')lua_tonumber(L,'..i..');')
end
elseif isBooleanType(ia) then
addLine(' '..ia.t..' '..ia.n..'=('..ia.t..')lua_toboolean(L,'..i..');')
elseif isAutoConversionType(ia) then
local cinfo=autoConversionType(ia)
local ia2={c=normalizeClassName(cinfo.convertTo)}
ia2.t=string.gsub(ia.t, ia.c, ia2.c)
--string.gsub(cinfo.forward,'%%', ...)
if not isLunaType(ia2) then
lgerror('Unsupported types for auto-conversion:', ia.c,'->',ia2.c)
else
--local t=string.gsub(ia.t,'%&','') -- remove reference
local t=ia2.t
local cp=findLunaClassProperty(ia2)
local cppclass_name=normalizedClassNameToClassName(cp.className)
local cppinterface_name=genInterfaceName(cp)
local cpp_parent_classname=normalizedClassNameToClassName(cp.uppermostParent.className)
local t_modifiers=string.gsub(t, normalizedClassNameToPattern(normalizeClassName(ia2.c)), '')
if select(1,string.find(t_modifiers,'*')) then
addLine(' '..t..' '..ia.n..'=static_cast<'..cppclass_name..' *>(Luna<'..cpp_parent_classname..' >::check(L,'..i..'));')
lgerror('this case has not yet been implemented')
else
local ii=string.find(ia2.t,'%&')
if not ii then t=t..'&' end -- add reference
addLine(' '..t..' '..ia.n..'__'..'=static_cast<'..cppclass_name..' &>(*Luna<'..cpp_parent_classname..' >::check(L,'..i..'));')
-- here, modifiers such as const& are dropped. ia.t contains modifiers, but ia.c does not.
addLine(' '..ia.c..' '..ia.n..'='..string.gsub(cinfo.backward,'%%%%',ia.n..'__')..';')
end
end
else
lgerror('Unknown or unsupported argument type: ',table.tostring(ia))
end
end
if vv.if_ then
addLine('#endif //'..vv.if_)
end
end
function addTypeCheck(args)
local debug_printf=gen_lua.generate_debug_printf
if debug_printf then
addLine('printf("luaget_top:%d\\n",lua_gettop(L));')
end
addLine(' if( lua_gettop(L)!='..#args..') return false;')
for i,ia in ipairs(args) do
if isLunaType(ia) then
local luaclass=findLunaClassProperty(ia)
if debug_printf then
addLine('printf("unique_id:%d=='..luaclass.uniqueID..'\\n",luna_t::get_uniqueid(L,'..i..'));')
end
assert(luaclass.uppermostParent.uniqueID)
addLine(' if( Luna<void>::get_uniqueid(L,'..i..')!='..luaclass.uppermostParent.uniqueID..') return false; // '..normalizedClassNameToClassName(luaclass.uppermostParent.className))
elseif isNumberType(ia) then
addLine(' if( lua_isnumber(L,'..i..')==0) return false;')
if debug_printf then
addLine('printf("lua_isnumber:%d\\n",lua_isnumber(L,'..i..'));')
end
elseif isStringType(ia) then
addLine(' if( lua_isstring(L,'..i..')==0) return false;')
if debug_printf then
addLine('printf("lua_isstring:%d\\n",lua_isstring(L,'..i..'));')
end
elseif isBooleanType(ia) then
addLine(' if( lua_isboolean(L,'..i..')==0) return false;')
if debug_printf then
addLine('printf("lua_isboolean:%d\\n",lua_isstring(L,'..i..'));')
end
elseif isAutoConversionType(ia) then
local luaclass=findLunaClassProperty({c=autoConversionType(ia).convertTo})
if debug_printf then
addLine('printf("unique_id:%d=='..luaclass.uniqueID..'\\n",luna_t::get_uniqueid(L,'..i..'));')
end
assert(luaclass.uppermostParent.uniqueID)
addLine(' if( Luna<void>::get_uniqueid(L,'..i..')!='..luaclass.uppermostParent.uniqueID..') return false; // '..normalizedClassNameToClassName(luaclass.uppermostParent.className))
else
lgerror('Unknown or unsupported argument type: ',table.tostring(ia))
end
end
addLine(' return true;\n }')
end
function write(ctn)
local lines=string.lines(ctn)
if verbose then
for i,l in ipairs(lines) do
print ("::"..ctn)
end
end
array.pushBack(gen_lua.cpp_contents, unpack(lines))
end
-- normalizeClassName using theree special character ` (means %s+) and ~ (means %s*) and @p (means * - pointer)
-- const char*, const char *, const\tchar\t*, and so on becomes 'const`char`@p'
-- std::string, std::vector<std::string>, and so on becomes
-- std~::~string, std~::~vector~<~std~::~string~>
-- the goal is that normalizeClassName should not be tokenized when using tokenizeArg function
gen_lua.normC={}
gen_lua.normC.token_sep={'::','<','>','%*',','} -- every tokens that can appear in a class type name
gen_lua.normC.token_conv={'@o','@s','@l', '@p', '@c'}
gen_lua.normC.token_pattern={'::','<','>','%%%*',','}
function patternToNormalizedClassName(classNamePattern)
local str=string.gsub(classNamePattern,'%%s%+','`')
str=string.gsub(str,'%%s%*','~')
local normC=gen_lua.normC
for i=1,#normC.token_sep do
str=string.gsub(str, normC.token_pattern[i], normC.token_conv[i])
end
return str
end
function normalizedClassNameToPattern(normalizedClassName)
local str=string.gsub(normalizedClassName,'`','%%s+')
str=string.gsub(str,'~','%%s*')
local normC=gen_lua.normC
for i=1,#normC.token_sep do
str=string.gsub(str, normC.token_conv[i], normC.token_pattern[i])
end
return str
end
function normalizedClassNameToClassName(normalizedClassName)
if normalizedClassName==nil then lgerror('normalizedClassName = nil') end
local str=string.gsub(normalizedClassName,'`',' ')
str=string.gsub(str,'~','')
local normC=gen_lua.normC
for i=1,#normC.token_sep do
str=string.gsub(str, normC.token_conv[i], ' '..normC.token_sep[i])
end
return str
end
function normalizeClassName(classNameOrPattern)
local str=classNameOrPattern
if select(1,string.find(str,'%%')) then
str=patternToNormalizedClassName(str)
end
local token_sep=gen_lua.normC.token_sep
local token_conv=gen_lua.normC.token_conv
local tokens=tokenizeArg(str, token_sep)
local sm={}
for i=1, #tokens do
for j=1, #token_sep do
if select(1,string.find(tokens[i],token_sep[j]))~=nil then
sm[i]=true
tokens[i]=token_conv[j]
break
end
end
end
local out=""
for i=1, #tokens-1 do
if sm[i] or sm[i+1] then
out=out..tokens[i].."~"
else
out=out..tokens[i].."`"
end
end
out=out..tokens[#tokens]
return out
end
-- e.g. str: (int x, double d)
-- return {{ t='int', n='x'}, {t='double', n='d'}}
function parseArg(str)
str=string.gsub(str,'static%s+','')
str=string.gsub(str, '%*', '* ') -- insert delimiting space
str=string.gsub(str, '>', '> ')
str=string.trimLeft(str)
str=string.trimRight(str)
if string.sub(str,-1)==';' then str=string.sub(str, 1,-2) end
if (string.sub(str,1,1)~='(' or string.sub(str,-1)~=')') then
lgerror('ctor', str, 'in unacceptable format. (ctor definition should start by ( and finish by ))')
end
for ictn,ctn in ipairs(gen_lua.complex_type_names) do
local newstr=string.gsub(str, ctn, patternToNormalizedClassName(ctn))
if verbose and str~=newstr then print('parseArg1', str, newstr) end
str=newstr
end
local args=string.tokenize(string.sub(str, 2, -2),',')
function isNonEmptyString(str)
local s=string.find(str,'^%s*$')
if s then
return false
end
return true
end
local args=array.filter(isNonEmptyString,args)
for iarg, arg in ipairs(args) do
local tokens=array.filter(isNonEmptyString, tokenizeArg(args[iarg],gen_lua.single_letter_modifiers))
local name=nil
local gmatched=nil
local typenames=gen_lua.type_names
for i=1,#tokens do
tokens[i]=string.trimSpaces(tokens[i])
-- print(tokens[i])
local matched=string.isLongestMatched(tokens[i],typenames, "[%(,]")
if not matched
and not string.isLongestMatched(tokens[i], gen_lua.modifiers)
and gen_lua.luna_types[tokens[i]]==nil
then
if i==#tokens then
name=tokens[i]
--elseif autoConversion then dbg.console()
else
lgerror('Error unknown type name : '..normalizedClassNameToClassName(args[iarg])..'\n'..gen_lua.type_error_msg)
end
end
if matched then
if gmatched==nil or ( #typenames[gmatched]<#typenames[matched]) then
-- prefer longer match
gmatched=matched
end
end
end
if gmatched==nil then lgerror('gmatched==nil arg:',arg) end
local ntc=normalizedClassNameToClassName
if name then
args[iarg]={ c=ntc(gen_lua.type_names[gmatched]), t=table.concat(array.map(ntc,tokens),' ', 1,#tokens-1), n=name}
else
args[iarg]={ c=ntc(gen_lua.type_names[gmatched]), t=table.concat(array.map(ntc,tokens),' '), n='_arg'..iarg}
end
if true then -- error checking
local aa=args[iarg]
local v_pattern=normalizedClassNameToPattern(aa.c)
local nn=string.gsub(aa.t, v_pattern, '')
local mod=gen_lua.modifiers
for md=1,#mod do
nn=string.gsub(nn, mod[md],'')
end
nn=string.gsub(nn, '%s+','')
if nn~='' then
lgerror('undefined type "'..aa.t..'" detected while parsing "'..str..'"!\n (did you mean '..aa.c..'? what is '..nn..'? Do not use variable names containing modifiers such as "const" or "virtual". ) \n '..gen_lua.type_error_msg)
end
end
end
--print(table.tostring(args))
return args
end
function rectifyFunctions(functions)
local output={}
if type(functions)=='string' then
--lgerror('string "'..functions..'" is given where table (of function defs) is expected')
functions={functions}
end
for i,v in ipairs(functions) do
if type(v)=="string" then
local lines=string.lines(v)
for il,l in ipairs(lines) do
local s=string.find(l,'//')
if s then l=string.sub(l, 1, s-1) end -- remove comments
local s=string.find(l,'@')
l=string.gsub(l, '%svirtual%s+',' ') -- remove virtual keyword
if s then -- parse options
local ren=string.trimSpaces(string.sub(l, s+1))
local options={}
while true do
local s,e,cc1,cc2=string.find(ren,'%;([^=]+)=([^%;]+)%;')
if s==nil then break end
options[cc1]=cc2
--ren=string.trimSpaces(string.gsub(ren,'%;[^=]+=[^%;]+%;',''))
ren=string.trimSpaces(string.sub(ren, 1,s-1)..string.sub(ren, e+1)..';')
end
ren=string.trimSpaces(string.gsub(ren, ';',''))
if #options>0 then printTable(options) end
if #ren~=0 then
options.rename=ren
end
l=string.sub(l, 1, s-1)
options[1]=l
array.pushBack(output, options)
else
local s=string.find(l,'^%s*$') -- discard empty
if not s then
if select(1,string.find(l,'/%*')) then
lgerror('block comment is not allowed:'.. l)
end
array.pushBack(output,l)
end
end
end
else
array.pushBack(output,v)
end
end
return output
end
function flushWritten(filename)
local ctx_new=table.concat(gen_lua.cpp_contents, '\n')
gen_lua.cpp_contents={}
if gen_lua.no_unmodified_overwriting then
if os.isFileExist(filename) then
local ctx_old=util.readFile(filename)
if ctx_old==ctx_new then
print('luna_gen won\'t overwrite "'..os.filename(filename)..'" because no change has made.')
return
end
end
end
print('generating '..filename)
util.writeFile(filename, ctx_new)
end
end
-- rectify function definitions
-- input: void asdf(int narg, std::string param)
-- output: {returnType= 'void', cppname='asdf', luaname='asdf', args={{t='int', n='nArg'},{t='std::string', n='param'}}}
-- note that this modifies bindTarget table significantly!
function buildDefinitionDB(...)
local targets={...}
if namespaces==nil then namespaces={} end
for i,bindTarget in ipairs(targets) do
if bindTarget.modules then
for k,v in ipairs(bindTarget.modules) do
if not v.namespace then
lgerror('module '..k..' does not have namespace')
end
v.namespace,v.name=string.rightTokenize(v.namespace, '%.')
if v.name=='_G' then
v.namespace='_G'
end
v.staticMemberFunctions=v.functions
v.isModule=true
end
if bindTarget.classes==nil then
print('bindTarget.classes==nil so making an empty one')
bindTarget.classes={}
end
if bindTarget.modules==nil then
print('bindTarget.modules==nil so making an empty one')
bindTarget.modules={}
end
array.concat(bindTarget.classes, bindTarget.modules) -- use the same code
end
if bindTarget.namespaces then
namespaces=table.merge(namespaces, bindTarget.namespaces)
end
end
local bindTarget
if #targets==1 then
bindTarget=targets[1]
else
bindTarget={}
bindTarget.modules={}
bindTarget.classes={}
for i,t in ipairs(targets) do -- shallow copy
array.pushBack(bindTarget.modules, unpack(t.modules))
array.pushBack(bindTarget.classes,unpack(t.classes))
end
end
assert(gen_lua.definitionDBbuilt==false)
for i=1,#gen_lua.number_types do
--print(gen_lua.number_types[i])
gen_lua.number_types[i]=normalizedClassNameToPattern(normalizeClassName(gen_lua.number_types[i]))
end
for i=1,#gen_lua.enum_types do
gen_lua.enum_types[i]=normalizedClassNameToPattern(normalizeClassName(gen_lua.enum_types[i]))
end
array.concat(gen_lua.type_names, array.map(normalizeClassName, gen_lua.number_types))
array.concat(gen_lua.type_names, array.map(normalizeClassName, gen_lua.enum_types))
array.concat(gen_lua.type_names, array.map(normalizeClassName, gen_lua.string_types))
array.concat(gen_lua.type_names, array.map(normalizeClassName, gen_lua.boolean_types))
if autoConversion then
if not gen_lua.autoConversion_rectified then
gen_lua.autoConversion_rectified={}
end
for k,v in pairs(autoConversion) do
local ncn=normalizeClassName(k)
array.pushBack(gen_lua.type_names, ncn)
gen_lua.autoConversion_rectified[ncn]=v
end
end
gen_lua.defNameSpaceCode=processNamespaces(namespaces, '_G.')
-- 1. collect class names
for iluaclass, luaclass in ipairs(bindTarget.classes) do
if luaclass.ifdef then
luaclass.if_='defined ('..luaclass.ifdef..')'
end
if luaclass.ifndef then
luaclass.if_='!defined ('..luaclass.ifndef..')'
end
-- automatic syntax corrections
for k, v in pairs(gen_lua.classProperty_name_translation) do
if luaclass[k] then
luaclass[v]=luaclass[k]
luaclass[k]=nil
end
end
-- automatic syntax corrections
if luaclass.inheritsFrom and select(1,string.find(luaclass.inheritsFrom,'%.')) then
luaclass.inheritsFrom=string.gsub(luaclass.inheritsFrom,"%.", "::")
end
if luaclass.decl and type(luaclass.decl)=='boolean' then
luaclass.decl='class '..luaclass.className..';'
luaclass.autodecl=nil
end
luaclass.name=string.gsub(luaclass.name,'::','%.')
for k,v in pairs(luaclass) do -- check syntax error of user-given definition
if not string.isMatched(k, gen_lua.supportedClassProperties) then
if luaclass.isModule then
if not string.isMatched(k, {'namespace', 'isModule', 'functions'}) then
lgerror('Syntax error: unknown property: ',k,'in',luaclass.name)
end
else
if tonumber(k) then
print('??? numbered index is not expected. ')
printTable(v)
end
lgerror('Syntax error: unknown property: ',k,'in',luaclass.name)
end
end
end
luaclass.iluaclass=iluaclass
luaclass.className=normalizeClassName(luaclass.className or
string.gsub(luaclass.name, '%.', '::'))
array.pushBack(gen_lua.type_names, luaclass.className)
-- if namespace (say NS) is defined,
-- two metatables are defined: