-
Notifications
You must be signed in to change notification settings - Fork 4
/
ffibuild.lua
executable file
·2179 lines (1752 loc) · 56.1 KB
/
ffibuild.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
do
_G[jit.os:upper()] = true
_G.OS = jit.os:lower()
_G[jit.arch:upper()] = true
_G.ARCH = jit.arch:lower()
UNIX = not WINDOWS
local ffi = require("ffi")
if WINDOWS then
function powershell(str, no_return)
os.setenv("pstemp", str)
local ps = "powershell -nologo -noprofile -noninteractive -command Invoke-Expression $Env:pstemp"
if no_return then
os.execute(ps)
return
end
local p = io.popen(ps)
local out = p:read("*all")
p:close()
return out
end
end
function os.readexecute(cmd)
return io.popen(cmd):read("*all")
end
function os.checkexecute(cmd)
local code
if UNIX then
code = os.readexecute(cmd .. " && printf %s $?")
else
code = os.readexecute(cmd .. " & echo %errorlevel%")
end
return code:sub(#code ) == "0"
end
do
local cache = {}
function os.iscmd(cmd)
if cache[cmd] ~= nil then return cache[cmd] end
local res
if WINDOWS then
res = os.readexecute("WHERE " .. cmd) ~= ""
else
res = os.readexecute("command -v " .. cmd) ~= ""
end
cache[cmd] = res
return res
end
end
function os.checkcmds(...)
local err = ""
for i,v in ipairs({...}) do
if not os.iscmd(v) then
err = v .. " is required\n"
end
end
if err ~= "" then
error(err, 2)
end
end
if UNIX then
ffi.cdef("char *getcwd(char *buf, size_t size);")
function os.getcd()
local buf = ffi.new("uint8_t[256]")
ffi.C.getcwd(buf, 256)
return ffi.string(buf)
end
else
ffi.cdef("unsigned long GetCurrentDirectoryA(unsigned long length, char *buffer);")
function os.getcd()
local buf = ffi.new("uint8_t[256]")
ffi.C.GetCurrentDirectoryA(256, buf)
return ffi.string(buf)
end
end
if UNIX then
function os.ls(path)
if path:sub(#path, #path) ~= "/" then
path = path .. "/"
end
local out = {}
for dir in os.readexecute("for dir in "..path.."*; do printf \"%s\n\" \"${dir}\"; done"):gmatch("(.-)\n") do
table.insert(out, dir:sub(#path + 1))
end
return out
end
else
function os.ls(path)
if path:sub(#path, #path) ~= "/" then
path = path .. "/"
end
path = os.getcd() .. "\\" .. path
path = path:gsub("/", "\\")
local out = {}
for name in os.readexecute("dir " .. path .. " /B"):gmatch("(.-)\n") do
table.insert(out, name)
end
return out
end
end
if UNIX then
ffi.cdef("int setenv(const char *name, const char *value, int overwrite);")
function os.setenv(key, val)
ffi.C.setenv(key, val, 0)
end
else
ffi.cdef("int _putenv_s(const char *var_name, const char *new_value);")
function os.setenv(key, val)
ffi.C._putenv_s(key, val)
end
end
function os.appendenv(key, val)
os.setenv(key, (os.getenv(key) or "") .. val)
end
function os.prependenv(key, val)
os.setenv(key, val .. (os.getenv(key) or ""))
end
if UNIX then
function os.pathtype(path)
if os.readexecute('[ -d "'..path..'" ] && printf "1"') == "1" then
return "directory"
elseif os.readexecute('[ -f "'..path..'" ] && printf "1"') == "1" then
return "file"
end
return nil
end
else
ffi.cdef([[
typedef struct goluwa_file_time {
unsigned long high;
unsigned long low;
} goluwa_file_time;
typedef struct goluwa_file_attributes {
unsigned long dwFileAttributes;
goluwa_file_time ftCreationTime;
goluwa_file_time ftLastAccessTime;
goluwa_file_time ftLastWriteTime;
unsigned long nFileSizeHigh;
unsigned long nFileSizeLow;
} goluwa_file_attributes;
bool GetFileAttributesExA(const char*, int, goluwa_file_attributes*);
]])
local flags = {
archive = 0x20, -- A file or directory that is an archive file or directory. Applications typically use this attribute to mark files for backup or removal .
compressed = 0x800, -- A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories.
device = 0x40, -- This value is reserved for system use.
directory = 0x10, -- The handle that identifies a directory.
encrypted = 0x4000, -- A file or directory that is encrypted. For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories.
hidden = 0x2, -- The file or directory is hidden. It is not included in an ordinary directory listing.
integrity_stream = 0x8000, -- The directory or user data stream is configured with integrity (only supported on ReFS volumes). It is not included in an ordinary directory listing. The integrity setting persists with the file if it's renamed. If a file is copied the destination file will have integrity set if either the source file or destination directory have integrity set.
normal = 0x80, -- A file that does not have other attributes set. This attribute is valid only when used alone.
not_content_indexed = 0x2000, -- The file or directory is not to be indexed by the content indexing service.
no_scrub_data = 0x20000, -- The user data stream not to be read by the background data integrity scanner (AKA scrubber). When set on a directory it only provides inheritance. This flag is only supported on Storage Spaces and ReFS volumes. It is not included in an ordinary directory listing.
offline = 0x1000, -- The data of a file is not available immediately. This attribute indicates that the file data is physically moved to offline storage. This attribute is used by Remote Storage, which is the hierarchical storage management software. Applications should not arbitrarily change this attribute.
readonly = 0x1, -- A file that is read-only. Applications can read the file, but cannot write to it or delete it. This attribute is not honored on directories. For more information, see You cannot view or change the Read-only or the System attributes of folders in Windows Server 2003, in Windows XP, in Windows Vista or in Windows 7.
reparse_point = 0x400, -- A file or directory that has an associated reparse point, or a file that is a symbolic link.
sparse_file = 0x200, -- A file that is a sparse file.
system = 0x4, -- A file or directory that the operating system uses a part of, or uses exclusively.
temporary = 0x100, -- A file that is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.
virtual = 0x10000, -- This value is reserved for system use.
}
function os.pathtype(path)
path = os.getcd() .. "\\" .. path
path = path:gsub("/", "\\")
local info = ffi.new("goluwa_file_attributes[1]")
if ffi.C.GetFileAttributesExA(path, 0, info) then
if
bit.bor(info[0].dwFileAttributes, flags.archive) == flags.archive or
bit.bor(info[0].dwFileAttributes, flags.normal) == flags.normal
then
return "file"
end
return "directory"
end
end
end
function os.isdir(dir) return os.pathtype(dir) == "directory" end
function os.isfile(dir) return os.pathtype(dir) == "file" end
if UNIX then
function os.makedir(dir)
return os.readexecute("mkdir -p " .. dir)
end
else
ffi.cdef("int SHCreateDirectoryExA(void *,const char *path, void *);")
local lib = ffi.load("Shell32.dll")
function os.makedir(dir)
return lib.SHCreateDirectoryExA(nil, dir, nil)
end
end
function os.download(url, to)
if WINDOWS then
if to then
to = os.getcd() .. "\\" .. to
return powershell("(New-Object System.Net.WebClient).DownloadFile('"..url.."', '"..to.."')") == ""
end
to = os.getcd() .. "\\" .. "temp_download"
powershell("(New-Object System.Net.WebClient).DownloadFile('"..url.."', '"..to.."')", true)
local content = io.readfile(to)
os.remove(to)
return content
else
if to then
if os.iscmd("wget") then
return os.readexecute("wget -O \""..to.."\" \""..url.."\" && printf $?") == "0"
elseif os.iscmd("curl") then
return os.readexecute("curl -L --url \""..url.."\" --output \""..to.."\" && printf $?") == "0"
end
end
if os.iscmd("wget") then
return os.readexecute("wget -qO- \""..url.."\"")
elseif os.iscmd("curl") then
return os.readexecute("curl -vv -L --url \""..url.."\"")
end
end
end
if UNIX then
ffi.cdef("int chdir(const char *path);")
function os.cd(path)
if ffi.C.chdir(path) ~= 0 then
return nil, "unable change directory to " .. path
end
return true
end
else
ffi.cdef("bool SetCurrentDirectoryA(const char *path);")
function os.cd(path)
if ffi.C.SetCurrentDirectoryA(path) == 0 then
return nil, "unable change directory to " .. path
end
return true
end
end
function io.readfile(path)
local f = assert(io.open(path))
local str = f:read("*all")
f:close()
return str
end
function io.writefile(path, str)
local f = assert(io.open(path, "w"))
f:write(str)
f:close()
end
function has_tmux_session()
return os.readexecute("tmux has-session -t goluwa 2> /dev/null; printf $?") == "0"
end
function os.extract(from, to, move_out)
if to:sub(#to, #to) ~= "/" then to = to .. "/" end
os.makedir(to)
if UNIX then
os.readexecute('tar -xvzf '..from..' -C "'..to..'"')
else
local to = to == "./" and "" or to
if false then
powershell([[
$file = "]]..os.getcd() .. "\\" .. from..[["
$location = "]]..os.getcd() .. "\\" .. to..[["
$shell = New-Object -Com Shell.Application
$zip = $shell.NameSpace($([System.IO.Path]::GetFullPath("$file")))
if (!$zip) {
Write-Error "could not extract $file!"
}
if (!(Test-Path $location)) {
New-Item -ItemType directory -Path $location | Out-Null
}
foreach($item in $zip.items()) {
$shell.Namespace("$location").CopyHere($item, 0x14)
}
]], true) end
end
if move_out then
move_out = to .. move_out
if move_out:sub(#move_out, #move_out) ~= "/" then
move_out = move_out .. "/"
end
repeat
local str, count = move_out:gsub("(.-/)(%*)(/.*)", function(left, star, right)
for k,v in ipairs(os.ls(left)) do
if os.isdir(left .. v) then
return left .. v .. right
end
end
end)
move_out = str
until count == 0
repeat
local str, count = move_out:gsub("(.-/)(.-%*)(/.*)", function(left, chunk, right)
for k,v in ipairs(os.ls(left)) do
if v:find(chunk:sub(0, -2), 0, true) and os.isdir(left .. v) then
return left .. v .. right
end
end
end)
move_out = str
until count == 0
if UNIX then
os.execute("cp -r " .. move_out .. "* " .. to)
local dir = move_out:sub(#to + 1):match("(.-)/")
if dir and os.isdir(to .. dir) then
os.execute("rm -rf " .. to .. dir)
end
else
powershell("Move-Item -Confirm:$false -Force -Path " .. move_out .. "* -Destination " .. to, true)
end
end
return true -- TODO
end
end
local ffibuild = {}
function ffibuild.Clone(str, dir)
dir = dir or "repo"
if str:find("%.git$") then
local url, branch = str:match("(.-github%.com/.-/.-)/tree/(.+)%.git$")
if url then
str = url
branch = "-b " .. branch
end
branch = branch or ""
os.execute("if [ -d ./" .. dir .. " ]; then git -C ./" .. dir .. " pull; else git clone " .. str .. " " .. dir .. " --depth 1 " .. branch .. " ; fi")
elseif str:find("hg%.") then
local clone_, branch = str:match("(.+);(.+)")
str = clone_ or str
if branch then
os.execute("hg clone " .. str .. " " .. dir .. " -r " .. branch)
else
os.execute("hg clone " .. str .. " " .. dir)
end
else
os.execute(str)
end
end
function ffibuild.ManualBuild(name, clone, build, copy)
--os.execute("git --git-dir=./repo/.git pull")
local ext = jit.os == "OSX" and ".dylib" or ".so"
local f = io.open("lib"..name..ext, "r")
if not f then
ffibuild.Clone(clone)
if build then
os.execute("cd repo && " .. build .. " && cd ..")
end
if not copy then
-- there's an -o switch for cp but depending on which one you find first it doesn't work
-- so screw it
os.execute("cp $(find . -name 'lib"..name.."*"..ext..".*' -type f -print -quit) lib"..name..ext)
local f = io.open("lib"..name..ext, "r")
if not f then
os.execute("cp $(find . -name 'lib"..name.."*"..ext.."' -type f -print -quit) lib"..name..ext)
else
f:close()
end
else
os.execute(copy)
end
else
f:close()
end
end
function ffibuild.NixBuild(data)
if not os.iscmd("nix-build") then
error("you need to install the nix package manager for ffibuild.NixBuild to work. See https://nixos.org/nix/", 2)
end
-- the output directory
local output_dir = os.getcd()
-- temporary filenames
local tmp_main = output_dir .. "/temp.c"
local tmp_out = "temp.p"
local tmp_nix = "temp.nix"
local build_phase
local build_phase_move
if data.src then
io.writefile(tmp_main, data.src)
build_phase = [[buildPhase = ''
gcc -xc -E -P -c ]] .. tmp_main .. [[ -o temp.p
'';]]
build_phase_move = "mv temp.p $out/temp.p; cp -r ${lib.getDev " .. data.package_name .. "}/include/* $out/include/;"
else
build_phase = "buildPhase = ''echo no build phase'';"
build_phase_move = ""
end
local lib_name
if data.library_name and data.library_name:sub(-1) == "*" then
lib_name = data.library_name
else
if not data.library_name then
lib_name = "lib" .. data.package_name
else
lib_name = data.library_name
end
lib_name = lib_name .. "." .. (OSX and "dylib" or UNIX and "so" or WINDOWS and "dll")
end
-- temporary default.nix file
io.writefile(tmp_nix,
[==[
with import <nixpkgs> {};
]==] .. (data.custom2 or "") .. [==[
stdenv.mkDerivation {
]==] .. (data.custom or "") .. [==[
name = "ffibuild_luajit";
src = ./.;
buildInputs = [ gcc (]==] .. data.package_name .. [==[) ];
]==] .. build_phase .. [==[
installPhase = ''
mkdir $out;
mkdir $out/include;
cp -L -r ${lib.getLib ]==] .. data.package_name .. [==[}/lib/]==] .. lib_name .. [==[ $out/.;
]==] .. build_phase_move .. [==[
'';
}
]==])
-- now execute nix-build
os.execute("nix-build --show-trace " .. tmp_nix)
-- return the preprocessed main.c file
local str
if data.src then
str = io.readfile("result/" .. tmp_out)
os.remove(tmp_main)
end
os.execute("cp -r -f result/* .")
--os.remove(tmp_nix)
if data.src then
os.remove(tmp_out)
end
return str
end
function ffibuild.ProcessSourceFileGCC(c_source, flags)
flags = flags or ""
local temp_name = os.tmpname()
local temp_file = io.open(temp_name, "w")
temp_file:write(c_source)
temp_file:close()
local gcc = io.popen("gcc -xc -E -P " .. flags .. " " .. temp_name)
local header = gcc:read("*all")
gcc:close()
os.remove(temp_name)
return header
end
function ffibuild.SplitHeader(header, ...)
header = header:gsub("/%*.-%*/", "")
local found = {}
for _, what in ipairs({...}) do
local _, stop_pos = header:find(".-" .. what)
if stop_pos then
stop_pos = stop_pos - #what
end
table.insert(found, stop_pos)
end
table.sort(found, function(a, b) return a < b end)
local stop = found[1]
for i = 1, math.huge do
local char = header:sub(stop - i, stop - i)
if char == ";" or char == "}" then
stop = stop - i + 1
break
end
end
return header:sub(0, stop), header:sub(stop)
end
local function match_type_declaration(str)
local declaration, name, array_size = str:match("^([%a%d%s_%*]-) ([%a%d_]-)$")
if not declaration then
declaration, name, array_size = str:match("^([%a%d%s_%*]-) ([%a%d_]-) (%[.+%])")
end
return declaration, name, array_size
end
function ffibuild.GetMetaData(header)
local meta_data = {
functions = {},
structs = {},
unions = {},
typedefs = {},
variables = {},
enums = {},
global_enums = {},
}
do -- cleanup header
-- this assumes the header has been preprocessed with gcc -E -P
header = " " .. header
-- process all single quote strings
header = header:gsub("('%S+')", function(val) return assert(loadstring("return (" .. val .. "):byte()"))() end)
header = header:gsub("' '", string.byte(" "))
-- remove comments
header = header:gsub("/%*.-%*/", "")
-- TODO: remove things like #pragma
header = header:gsub("#.-\n", "")
-- normalize everything to have equal spacing even between punctation
header = header:gsub("([*%(%){}&%[%],;&|<>=])", " %1 ")
header = header:gsub("%s+", " ")
-- insert a newline after ;
header = header:gsub(";", ";\n")
-- this will explode structs and and whatnot so make sure we remove newlines inside {} and ()
header = header:gsub("%b{}", function(s) return s:gsub("%s+", " ") end)
header = header:gsub("%b()", function(s) return s:gsub("%s+", " ") end)
--TODO
-- remove compiler __attribute__
header = header:gsub("__%a-__ %b() ", "")
-- remove __extension__
header = header:gsub("__extension__ ", "")
-- remove __restrict
header = header:gsub("__restrict__ ", "")
header = header:gsub("__restrict", "")
header = header:gsub("__max_align_..", "")
-- remove volatile
header = header:gsub(" volatile ", " ")
-- clang specific
header = header:gsub(" _Nullable ", " ")
-- remove inline functions
header = header:gsub(" static __inline.-%b().-%b{}", "")
header = header:gsub(" static inline.-%b().-%b{}", "")
header = header:gsub(" extern __inline.-%b().-%b{}", "")
header = header:gsub(" extern inline.-%b().-%b{}", "")
-- int foo(void); >> int foo();
header = header:gsub(" %( void %) ", " ( ) ")
-- TODO: support more than 2 definitions
-- struct foo {} foo_t, * pfoo_t;
-- >>
-- struct foo {} foo_t;
-- struct foo {} * pfoo_t;
header = header:gsub("typedef %a- [%a%d_]+ %b{} [^;]- ;", function(statement)
if statement:find(",") then
local tag, huh = statement:match("^typedef (%a- [%a%d_]+) %b{} .+,(.+);$")
if tag then
return statement:match("(typedef %a- [%a%d_]+ %b{} .-),") .. ";\n" .. "typedef " .. tag .. huh .. ";"
end
end
end)
-- void * foo ( int , int ) >> void * ( foo ) ( int , int )
-- this makes things easier to parse
header = header:gsub("([^\n]-) ([%a%d_]+) (%b() ;)", function(a,b,c)
local line = a .. " ( " .. b .. " ) " .. c
line = line:gsub("%( %(", "(")
line = line:gsub("%) %)", ")")
return line
end)
-- extern int foo, bar, faz;
-- >>
-- extern int foo;
-- extern int bar;
-- extern int faz;
header = header:gsub("extern (.-);", function(s)
if s:find(",", nil, true) and not s:find("(", nil, true) and not s:find("{", nil, true) then
local names = {}
s = s .. ", "
s = s:gsub(" ([%a%d_]+) ,", function(name)
table.insert(names, name)
return ""
end)
local new_str = ""
for _, name in ipairs(names) do
new_str = new_str .. " extern " .. s .. name .. " ;\n"
end
return new_str:sub(2, -2) -- get rid of exessive whitespace
end
end)
end
local function is_function(str) return str:find("^.-%b() %b() $") end
local i = 1
local function create_type(...)
local t = ffibuild.CreateType(...)
t.i = i
return t
end
for line in header:gmatch(" (.-);\n") do
local extern
local typedef
if line:find("^typedef") then
typedef = true
line = line:match("^typedef (.+)")
if is_function(line) then
local type = create_type("function", line:sub(0, -2), meta_data)
meta_data.typedefs[type.name] = type
line = nil
else
local content, alias = line:match("^(.+) ([%a%d_]+)")
if content:find("^struct ") or content:find("^union ") or content:find("^enum ") then
local tag, found = content:gsub(" %b{}", "")
if not tag:find("%s") then
tag = tag .. " " .. alias
content = content:gsub("^(%l+ )", tag .. " ")
end
meta_data.typedefs[alias] = create_type("type", tag)
line = content
else
local array_size
if line:find("%b[]") then
content, alias, arr = line:match("^(.+) ([%a%d_]+) (%b[])")
array_size = arr
end
meta_data.typedefs[alias] = create_type("type", content, array_size)
line = nil
end
end
elseif line:find("^extern") then
extern = true
line = line:match("^extern (.+)")
--elseif line:find("^static") then
-- print(line)
end
if line then
if is_function(line) then
local type = create_type("function", line:sub(0, -2), meta_data)
meta_data.functions[type.name] = type
elseif line:find("^enum") then
local tag, content = line:match("(enum [%a%d_]+) ({.+})")
if tag then
local test = tag:match("^enum (.+)")
if meta_data.typedefs[test] and meta_data.typedefs[test]:GetBasicType() == "int" then
meta_data.typedefs[test].last_node.type = tag
meta_data.typedefs[test].last_node.enum = true
end
meta_data.enums[tag] = create_type("enums", content, meta_data)
meta_data.enums[tag].name = tag
else
content = line:match("enum ({.+})")
-- no type name = global enum
table.insert(meta_data.global_enums, create_type("enums", content, meta_data))
end
elseif line:find("^struct") or line:find("^union") then
local keyword = line:match("^([%a%d_]+)")
local tag, content = line:match("("..keyword.." [%a%d_]+) ({.+})")
if not tag then
-- just a forward declaration or an opaque struct
tag = line:match("("..keyword.." [%a%d_]+)")
content = "{ }"
end
local tbl = keyword == "struct" and meta_data.structs or meta_data.unions
if not tbl[tag] or tbl[tag]:GetDeclaration():find("{%s+}") then
tbl[tag] = create_type("struct", content, keyword == "union", meta_data)
end
elseif extern then
local declaration, name, array_size = match_type_declaration(line:sub(0, -2))
meta_data.variables[name] = create_type("type", declaration, array_size)
end
end
i = i + 1
end
function meta_data:GetStructTypes(pattern)
local out = {}
-- find all types that start with *pattern* and are also structs
for type_name, type in pairs(self.typedefs) do
local name = type_name:match(pattern)
if name and type:GetSubType() == "struct" then
table.insert(out, {
name = name,
type = type,
})
end
end
-- sort them by length to avoid functions like purple_>>conversation<<_foo_bar() to conflict with purple_>>conversation_im<<_foo_bar()
table.sort(out, function(a, b) return #a.name > #b.name end)
return out
end
function meta_data:GetFunctionsStartingWithType(type)
local out = {}
for func_name, func_type in pairs(self.functions) do
if func_type.arguments then
local evaluated = func_type.arguments[1]
if evaluated:GetBasicType(self) == type:GetBasicType(self) then
out[func_name] = func_type
end
end
end
return out
end
function meta_data:FindFunctions(pattern, from, to)
local out = {}
for func_name, func_type in pairs(self.functions) do
local capture = func_name:match(pattern)
if capture then
if from and to then
capture = ffibuild.ChangeCase(capture, from, to)
end
out[capture] = func_type
end
end
return out
end
function meta_data:BuildMinimalHeader(check_function, check_enum, keep_structs, iterate_all_enums)
local required = {}
local bottom = ""
for func_name, func_type in pairs(self.functions) do
if not check_function or check_function(func_name, func_type) then
func_type:FetchRequired(self, required)
bottom = bottom .. func_type:GetDeclaration(self) .. ";\n"
end
end
local top = ""
-- global enums
if #self.global_enums > 0 then
local str = {}
for i, enums in ipairs(self.global_enums) do
local line = {}
for _, v in ipairs(enums:FetchEnums(check_enum)) do
table.insert(line, v)
end
if #line > 0 then
table.insert(str, table.concat(line, ",") .. ",")
end
end
if #str > 0 then
top = top .. "enum {" .. table.concat(str, "\n") .. "};"
end
end
-- typedef enums
if iterate_all_enums then
for name, enums in pairs(self.enums) do
local declaration = enums:GetDeclaration(self, check_enum)
if declaration then
top = top .. declaration .. "\n"
end
end
else
for _, type in pairs(required) do
if type:GetSubType() == "enum" then
local enums = self.enums[type:GetBasicType(self)]
local declaration = enums:GetDeclaration(self, check_enum)
if declaration then
top = top .. declaration .. "\n"
end
end
end
end
local temp = {}
for _, type in pairs(required) do
local basic_type = type:GetBasicType(self)
if type:GetSubType() == "struct" then
if self.structs[basic_type] then
table.insert(temp, {type = type, i = self.structs[basic_type].i})
end
elseif type:GetSubType() == "union" then
if self.unions[basic_type] then
table.insert(temp, {type = type, i = self.unions[basic_type].i})
end
end
end
table.sort(temp, function(a, b) return a.i < b.i end)
required = temp
for _, val in ipairs(required) do
local type = val.type
local basic_type = type:GetBasicType(self)
if type:GetSubType() == "struct" then
if keep_structs then
top = top .. basic_type .. " " .. self.structs[basic_type]:GetDeclaration(self) .. ";\n"
else
top = top .. basic_type .. " { };\n"
end
elseif type:GetSubType() == "union" then
if keep_structs then
top = top .. basic_type .. " " .. self.unions[basic_type]:GetDeclaration(self) .. ";\n"
else
top = top .. basic_type .. " { };\n"
end
end
end
local header = top .. bottom
--struct _GList { void * data; struct _GList * next; struct _GList * prev; };
header = header:gsub(" ([^%a%d%s_])", "%1"):gsub("([^%a%d%s_]) ", "%1")
--struct _GList{void*data;struct _GList*next;struct _GList*prev;};
return header
end
function meta_data:BuildFunctions(pattern, from, to, clib, callback)
local s = "{\n"
for func_name, func_type in pairs(self.functions) do
if not callback or callback(func_type.name) ~= false then
local friendly_name
if pattern then
friendly_name = func_name:match(pattern)
else
friendly_name = func_name
end
if friendly_name then
if from then friendly_name = ffibuild.ChangeCase(friendly_name, from, to) end
s = s .. "\t" .. friendly_name .. " = " .. ffibuild.BuildLuaFunction(func_type.name, func_type, nil, nil, nil, clib) .. ",\n"
end
end
end
s = s .. "}\n"
return s
end
do
local function get_enum_name(name, pattern, group, basic_type)
if not pattern and group then
if basic_type:find(group) then
return name
end
end
local key
if pattern then
key = name:match(pattern)
else
key = name
end
-- if the prefix has been stripped the key might start with a number
if key and key:find("^%d") then
print("enum " .. key .. " starts with a number. prepending _")
key = "_" .. key
end
return key
end
function meta_data:BuildEnums(pattern, define_file, define_starts_with, group)
local s = "{\n"
for basic_type, type in pairs(self.enums) do
for _, enum in ipairs(type.enums) do
local key = get_enum_name(enum.key, pattern, group, basic_type)
if key then
s = s .. "\t" .. key .. " = ffi.cast(\""..basic_type.."\", \""..enum.key.."\"),\n"
end
end
end
if not group then
for _, enums in pairs(self.global_enums) do
for _, enum in ipairs(enums.enums) do
local key = get_enum_name(enum.key, pattern, group, basic_type)
if key then