/
gen_lua_ffi.lua
1696 lines (1551 loc) · 47.5 KB
/
gen_lua_ffi.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
-- Copyright (c) 2010 by Robert G. Jakabosky <bobby@neoawareness.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- build LuaJIT FFI bindings
--
local ffi_helper_types = [[
#if LUAJIT_FFI
typedef int (*ffi_export_func_t)(void);
typedef struct ffi_export_symbol {
const char *name;
union {
void *data;
ffi_export_func_t func;
} sym;
} ffi_export_symbol;
#endif
]]
local objHelperFunc = [[
#if LUAJIT_FFI
/* nobj_ffi_support_enabled_hint should be set to 1 when FFI support is enabled in at-least one
* instance of a LuaJIT state. It should never be set back to 0. */
static int nobj_ffi_support_enabled_hint = 0;
static const char nobj_ffi_support_key[] = "LuaNativeObject_FFI_SUPPORT";
static const char nobj_check_ffi_support_code[] =
"local stat, ffi=pcall(require,\"ffi\")\n" /* try loading LuaJIT`s FFI module. */
"if not stat then return false end\n"
"return true\n";
static int nobj_check_ffi_support(lua_State *L) {
int rc;
int err;
/* check if ffi test has already been done. */
lua_pushstring(L, nobj_ffi_support_key);
lua_rawget(L, LUA_REGISTRYINDEX);
if(!lua_isnil(L, -1)) {
rc = lua_toboolean(L, -1);
lua_pop(L, 1);
/* use results of previous check. */
goto finished;
}
lua_pop(L, 1); /* pop nil. */
err = luaL_loadbuffer(L, nobj_check_ffi_support_code,
sizeof(nobj_check_ffi_support_code) - 1, nobj_ffi_support_key);
if(0 == err) {
err = lua_pcall(L, 0, 1, 0);
}
if(err) {
const char *msg = "<err not a string>";
if(lua_isstring(L, -1)) {
msg = lua_tostring(L, -1);
}
printf("Error when checking for FFI-support: %s\n", msg);
lua_pop(L, 1); /* pop error message. */
return 0;
}
/* check results of test. */
rc = lua_toboolean(L, -1);
lua_pop(L, 1); /* pop results. */
/* cache results. */
lua_pushstring(L, nobj_ffi_support_key);
lua_pushboolean(L, rc);
lua_rawset(L, LUA_REGISTRYINDEX);
finished:
/* turn-on hint that there is FFI code enabled. */
if(rc) {
nobj_ffi_support_enabled_hint = 1;
}
return rc;
}
typedef struct {
const char **ffi_init_code;
int offset;
} nobj_reader_state;
static const char *nobj_lua_Reader(lua_State *L, void *data, size_t *size) {
nobj_reader_state *state = (nobj_reader_state *)data;
const char *ptr;
(void)L;
ptr = state->ffi_init_code[state->offset];
if(ptr != NULL) {
*size = strlen(ptr);
state->offset++;
} else {
*size = 0;
}
return ptr;
}
static int nobj_try_loading_ffi(lua_State *L, const char *ffi_mod_name,
const char *ffi_init_code[], const ffi_export_symbol *ffi_exports, int priv_table)
{
nobj_reader_state state = { ffi_init_code, 0 };
int err;
/* export symbols to priv_table. */
while(ffi_exports->name != NULL) {
lua_pushstring(L, ffi_exports->name);
lua_pushlightuserdata(L, ffi_exports->sym.data);
lua_settable(L, priv_table);
ffi_exports++;
}
err = lua_load(L, nobj_lua_Reader, &state, ffi_mod_name);
if(0 == err) {
lua_pushvalue(L, -2); /* dup C module's table. */
lua_pushvalue(L, priv_table); /* move priv_table to top of stack. */
lua_remove(L, priv_table);
lua_pushvalue(L, LUA_REGISTRYINDEX);
err = lua_pcall(L, 3, 0, 0);
}
if(err) {
const char *msg = "<err not a string>";
if(lua_isstring(L, -1)) {
msg = lua_tostring(L, -1);
}
printf("Failed to install FFI-based bindings: %s\n", msg);
lua_pop(L, 1); /* pop error message. */
}
return err;
}
#endif
]]
local module_init_src = [[
#if LUAJIT_FFI
if(nobj_check_ffi_support(L)) {
nobj_try_loading_ffi(L, "${module_c_name}.nobj.ffi.lua", ${module_c_name}_ffi_lua_code,
${module_c_name}_ffi_export, priv_table);
}
#endif
]]
local submodule_init_src = [[
#if ${module_c_name}_${object_name}_LUAJIT_FFI
if(nobj_check_ffi_support(L)) {
nobj_try_loading_ffi(L, "${module_c_name}_${object_name}",
${module_c_name}_${object_name}_ffi_lua_code,
${module_c_name}_${object_name}_ffi_export, priv_table);
}
#endif
]]
--
-- FFI templates
--
local ffi_helper_code = [===[
local ffi=require"ffi"
local function ffi_safe_load(name, global)
local stat, C = pcall(ffi.load, name, global)
if not stat then return nil, C end
if global then return ffi.C end
return C
end
local function ffi_load(name, global)
return assert(ffi_safe_load(name, global))
end
local function ffi_string(ptr)
if ptr ~= nil then
return ffi.string(ptr)
end
return nil
end
local function ffi_string_len(ptr, len)
if ptr ~= nil then
return ffi.string(ptr, len)
end
return nil
end
local f_cast = ffi.cast
local pcall = pcall
local error = error
local type = type
local tonumber = tonumber
local tostring = tostring
local sformat = require"string".format
local rawset = rawset
local setmetatable = setmetatable
local package = (require"package") or {}
local p_config = package.config
local p_cpath = package.cpath
local ffi_load_cmodule
-- try to detect luvit.
if p_config == nil and p_cpath == nil then
ffi_load_cmodule = function(name, global)
for path,module in pairs(package.loaded) do
if module == name then
local C, err = ffi_safe_load(path, global)
-- return opened library
if C then return C end
end
end
error("Failed to find: " .. name)
end
else
ffi_load_cmodule = function(name, global)
local dir_sep = p_config:sub(1,1)
local path_sep = p_config:sub(3,3)
local path_mark = p_config:sub(5,5)
local path_match = "([^" .. path_sep .. "]*)" .. path_sep
-- convert dotted name to directory path.
name = name:gsub('%.', dir_sep)
-- try each path in search path.
for path in p_cpath:gmatch(path_match) do
local fname = path:gsub(path_mark, name)
local C, err = ffi_safe_load(fname, global)
-- return opened library
if C then return C end
end
error("Failed to find: " .. name)
end
end
local _M, _priv, reg_table = ...
local REG_MODULES_AS_GLOBALS = false
local REG_OBJECTS_AS_GLOBALS = false
local C = ffi.C
local OBJ_UDATA_FLAG_OWN = 1
local function ffi_safe_cdef(block_name, cdefs)
local fake_type = "struct sentinel_" .. block_name .. "_ty"
local stat, size = pcall(ffi.sizeof, fake_type)
if stat and size > 0 then
-- already loaded this cdef block
return
end
cdefs = fake_type .. "{ int a; int b; int c; };" .. cdefs
return ffi.cdef(cdefs)
end
ffi_safe_cdef("LuaNativeObjects", [[
typedef struct obj_type obj_type;
typedef void (*base_caster_t)(void **obj);
typedef void (*dyn_caster_t)(void **obj, obj_type **type);
struct obj_type {
dyn_caster_t dcaster; /**< caster to support casting to sub-objects. */
int32_t id; /**< type's id. */
uint32_t flags; /**< type's flags (weak refs) */
const char *name; /**< type's object name. */
};
typedef struct obj_base {
int32_t id;
base_caster_t bcaster;
} obj_base;
typedef struct obj_udata {
void *obj;
uint32_t flags; /**< lua_own:1bit */
} obj_udata;
int memcmp(const void *s1, const void *s2, size_t n);
]])
local nobj_callback_states = {}
local nobj_weak_objects = setmetatable({}, {__mode = "v"})
local nobj_obj_flags = {}
local function obj_ptr_to_id(ptr)
return tonumber(f_cast('uintptr_t', ptr))
end
local function obj_to_id(ptr)
return tonumber(f_cast('uintptr_t', f_cast('void *', ptr)))
end
local function register_default_constructor(_pub, obj_name, constructor)
local obj_pub = _pub[obj_name]
if type(obj_pub) == 'table' then
-- copy table since it might have a locked metatable
local new_pub = {}
for k,v in pairs(obj_pub) do
new_pub[k] = v
end
setmetatable(new_pub, { __call = function(t,...)
return constructor(...)
end,
__metatable = false,
})
obj_pub = new_pub
else
obj_pub = constructor
end
_pub[obj_name] = obj_pub
_M[obj_name] = obj_pub
if REG_OBJECTS_AS_GLOBALS then
_G[obj_name] = obj_pub
end
end
]===]
-- templates for typed *_check/*_delete/*_push functions
local ffi_obj_type_check_delete_push = {
['simple'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
ffi_safe_cdef("${object_name}_simple_wrapper", [=[
struct ${object_name}_t {
const ${object_name} _wrapped_val;
};
typedef struct ${object_name}_t ${object_name}_t;
]=])
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name}_t")
function obj_type_${object_name}_check(obj)
return obj._wrapped_val
end
function obj_type_${object_name}_delete(obj)
local id = obj_to_id(obj)
local valid = nobj_obj_flags[id]
if not valid then return nil end
local val = obj._wrapped_val
nobj_obj_flags[id] = nil
return val
end
function obj_type_${object_name}_push(val)
local obj = obj_ctype(val)
local id = obj_to_id(obj)
nobj_obj_flags[id] = true
return obj
end
function obj_mt:__tostring()
return sformat("${object_name}: %d", tonumber(self._wrapped_val))
end
function obj_mt.__eq(val1, val2)
if not ffi.istype(obj_ctype, val2) then return false end
return (val1._wrapped_val == val2._wrapped_val)
end
-- type checking function for C API.
_priv[obj_type] = function(obj)
if ffi.istype(obj_ctype, obj) then return obj._wrapped_val end
return nil
end
-- push function for C API.
reg_table[obj_type] = function(ptr)
return obj_type_${object_name}_push(ffi.cast("${object_name} *", ptr)[0])
end
end
]],
['simple ptr'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name} *")
function obj_type_${object_name}_check(ptr)
return ptr
end
function obj_type_${object_name}_delete(ptr)
local id = obj_ptr_to_id(ptr)
local flags = nobj_obj_flags[id]
if not flags then return ptr end
ffi.gc(ptr, nil)
nobj_obj_flags[id] = nil
return ptr
end
if obj_mt.__gc then
-- has __gc metamethod
function obj_type_${object_name}_push(ptr)
local id = obj_ptr_to_id(ptr)
nobj_obj_flags[id] = true
return ffi.gc(ptr, obj_mt.__gc)
end
else
-- no __gc metamethod
function obj_type_${object_name}_push(ptr)
return ptr
end
end
function obj_mt:__tostring()
return sformat("${object_name}: %p", self)
end
-- type checking function for C API.
_priv[obj_type] = function(ptr)
if ffi.istype(obj_ctype, ptr) then return ptr end
return nil
end
-- push function for C API.
reg_table[obj_type] = function(ptr)
return obj_type_${object_name}_push(ffi.cast(obj_ctype, ptr)[0])
end
end
]],
['embed'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name}")
local ${object_name}_sizeof = ffi.sizeof"${object_name}"
function obj_type_${object_name}_check(obj)
return obj
end
function obj_type_${object_name}_delete(obj)
return obj
end
function obj_type_${object_name}_push(obj)
return obj
end
function obj_mt:__tostring()
return sformat("${object_name}: %p", self)
end
function obj_mt.__eq(val1, val2)
if not ffi.istype(obj_type, val2) then return false end
assert(ffi.istype(obj_type, val1), "expected ${object_name}")
return (C.memcmp(val1, val2, ${object_name}_sizeof) == 0)
end
-- type checking function for C API.
_priv[obj_type] = function(obj)
if ffi.istype(obj_type, obj) then return obj end
return nil
end
-- push function for C API.
reg_table[obj_type] = function(ptr)
local obj = obj_ctype()
ffi.copy(obj, ptr, ${object_name}_sizeof);
return obj
end
end
]],
['object id'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
ffi_safe_cdef("${object_name}_simple_wrapper", [=[
struct ${object_name}_t {
const ${object_name} _wrapped_val;
};
typedef struct ${object_name}_t ${object_name}_t;
]=])
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name}_t")
function obj_type_${object_name}_check(obj)
-- if obj is nil or is the correct type, then just return it.
if not obj or ffi.istype(obj_ctype, obj) then return obj._wrapped_val end
-- check if it is a compatible type.
local ctype = tostring(ffi.typeof(obj))
local bcaster = _obj_subs.${object_name}[ctype]
if bcaster then
return bcaster(obj._wrapped_val)
end
return error("Expected '${object_name}'", 2)
end
function obj_type_${object_name}_delete(obj)
local id = obj_to_id(obj)
local flags = nobj_obj_flags[id]
local val = obj._wrapped_val
if not flags then return nil, 0 end
nobj_obj_flags[id] = nil
return val, flags
end
function obj_type_${object_name}_push(val, flags)
local obj = obj_ctype(val)
local id = obj_to_id(obj)
nobj_obj_flags[id] = flags
return obj
end
function obj_mt:__tostring()
local val = self._wrapped_val
return sformat("${object_name}: %d, flags=%d",
tonumber(val), nobj_obj_flags[obj_to_id(val)] or 0)
end
function obj_mt.__eq(val1, val2)
if not ffi.istype(obj_ctype, val2) then return false end
return (val1._wrapped_val == val2._wrapped_val)
end
-- type checking function for C API.
_priv[obj_type] = obj_type_${object_name}_check
-- push function for C API.
reg_table[obj_type] = function(ptr, flags)
return obj_type_${object_name}_push(ffi.cast('uintptr_t',ptr), flags)
end
end
]],
['generic'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name} *")
function obj_type_${object_name}_check(ptr)
-- if ptr is nil or is the correct type, then just return it.
if not ptr or ffi.istype(obj_ctype, ptr) then return ptr end
-- check if it is a compatible type.
local ctype = tostring(ffi.typeof(ptr))
local bcaster = _obj_subs.${object_name}[ctype]
if bcaster then
return bcaster(ptr)
end
return error("Expected '${object_name} *'", 2)
end
function obj_type_${object_name}_delete(ptr)
local id = obj_ptr_to_id(ptr)
local flags = nobj_obj_flags[id]
if not flags then return nil, 0 end
ffi.gc(ptr, nil)
nobj_obj_flags[id] = nil
return ptr, flags
end
function obj_type_${object_name}_push(ptr, flags)
${dyn_caster}
if flags ~= 0 then
local id = obj_ptr_to_id(ptr)
nobj_obj_flags[id] = flags
ffi.gc(ptr, obj_mt.__gc)
end
return ptr
end
function obj_mt:__tostring()
return sformat("${object_name}: %p, flags=%d", self, nobj_obj_flags[obj_ptr_to_id(self)] or 0)
end
-- type checking function for C API.
_priv[obj_type] = obj_type_${object_name}_check
-- push function for C API.
reg_table[obj_type] = function(ptr, flags)
return obj_type_${object_name}_push(ffi.cast(obj_ctype,ptr), flags)
end
end
]],
['generic_weak'] = [[
local obj_type_${object_name}_check
local obj_type_${object_name}_delete
local obj_type_${object_name}_push
do
local obj_mt, obj_type, obj_ctype = obj_register_ctype("${object_name}", "${object_name} *")
function obj_type_${object_name}_check(ptr)
-- if ptr is nil or is the correct type, then just return it.
if not ptr or ffi.istype(obj_ctype, ptr) then return ptr end
-- check if it is a compatible type.
local ctype = tostring(ffi.typeof(ptr))
local bcaster = _obj_subs.${object_name}[ctype]
if bcaster then
return bcaster(ptr)
end
return error("Expected '${object_name} *'", 2)
end
function obj_type_${object_name}_delete(ptr)
local id = obj_ptr_to_id(ptr)
local flags = nobj_obj_flags[id]
if not flags then return nil, 0 end
ffi.gc(ptr, nil)
nobj_obj_flags[id] = nil
return ptr, flags
end
function obj_type_${object_name}_push(ptr, flags)
local id = obj_ptr_to_id(ptr)
-- check weak refs
if nobj_obj_flags[id] then return nobj_weak_objects[id] end
${dyn_caster}
if flags ~= 0 then
nobj_obj_flags[id] = flags
ffi.gc(ptr, obj_mt.__gc)
end
nobj_weak_objects[id] = ptr
return ptr
end
function obj_mt:__tostring()
return sformat("${object_name}: %p, flags=%d", self, nobj_obj_flags[obj_ptr_to_id(self)] or 0)
end
-- type checking function for C API.
_priv[obj_type] = obj_type_${object_name}_check
-- push function for C API.
reg_table[obj_type] = function(ptr, flags)
return obj_type_${object_name}_push(ffi.cast(obj_ctype,ptr), flags)
end
end
]],
}
local ffi_obj_metatype = {
['simple'] = "${object_name}_t",
['simple ptr'] = "${object_name}_t",
['embed'] = "${object_name}",
['object id'] = "${object_name}_t",
['generic'] = nil,
['generic_weak'] = "${object_name}",
}
local function get_var_name(var)
local name = 'self'
if not var.is_this then
name = '${' .. var.name .. '}'
end
return name
end
local function unwrap_value(self, var)
local name = get_var_name(var)
return name .. ' = ' .. name .. '._wrapped_val\n'
end
local function no_wrapper(self, var) return '\n' end
local ffi_obj_type_check = {
['simple'] = unwrap_value,
['simple ptr'] = no_wrapper,
['embed'] = no_wrapper,
['object id'] = unwrap_value,
['generic'] = no_wrapper,
['generic_weak'] = no_wrapper,
}
-- module template
local ffi_module_template = [==[
local _obj_interfaces_ffi = {}
local _pub = {}
local _meth = {}
local _push = {}
local _obj_subs = {}
for obj_name,mt in pairs(_priv) do
if type(mt) == 'table' then
_obj_subs[obj_name] = {}
if mt.__index then
_meth[obj_name] = mt.__index
end
end
end
for obj_name,pub in pairs(_M) do
_pub[obj_name] = pub
end
--
-- CData Metatable access
--
local _ctypes = {}
local _type_names = {}
local _get_mt_key = {}
local _ctype_meta_map = {}
local f_typeof = ffi.typeof
local function get_cdata_type_id(cdata)
return tonumber(f_typeof(cdata))
end
local function get_cdata_mt(cdata)
return _ctype_meta_map[tonumber(f_typeof(cdata))]
end
local function obj_register_ctype(name, ctype)
local obj_mt = _priv[name]
local obj_type = obj_mt['.type']
local obj_ctype = ffi.typeof(ctype)
local obj_type_id = tonumber(obj_ctype)
_ctypes[name] = obj_ctype
_type_names[name] = tostring(obj_ctype)
_ctype_meta_map[obj_type_id] = obj_mt
_ctype_meta_map[obj_mt] = obj_type_id
return obj_mt, obj_type, obj_ctype
end
--
-- Interfaces helper code.
--
local _obj_interfaces_key = "obj_interfaces<1.0>_table_key"
local _obj_interfaces_ud = reg_table[_obj_interfaces_key]
local _obj_interfaces_key_ffi = _obj_interfaces_key .. "_LJ2_FFI"
_obj_interfaces_ffi = reg_table[_obj_interfaces_key_ffi]
if not _obj_interfaces_ffi then
-- create missing interfaces table for FFI bindings.
_obj_interfaces_ffi = {}
reg_table[_obj_interfaces_key_ffi] = _obj_interfaces_ffi
end
local function obj_get_userdata_interface(if_name, expected_err)
local impls_ud = _obj_interfaces_ud[if_name]
if not impls_ud then
impls_ud = {}
_obj_interfaces_ud[if_name] = impls_ud
end
-- create cdata check function to be used by non-ffi bindings.
if not impls_ud.cdata then
function impls_ud.cdata(obj)
return assert(impls_ud[get_cdata_mt(obj)], expected_err)
end
end
return impls_ud
end
local function obj_get_interface_check(if_name, expected_err)
local impls_ffi = _obj_interfaces_ffi[if_name]
if not impls_ffi then
local if_type = ffi.typeof(if_name .. " *")
local impls_ud = obj_get_userdata_interface(if_name, expected_err)
-- create table for FFI-based interface implementations.
impls_ffi = setmetatable({}, {
__index = function(impls_ffi, mt)
local impl = impls_ud[mt]
if impl then
-- cast to cdata
impl = if_type(impl)
rawset(impls_ffi, mt, impl)
end
return impl
end})
_obj_interfaces_ffi[if_name] = impls_ffi
-- create check function for this interface.
function impls_ffi.check(obj)
local impl
if type(obj) == 'cdata' then
impl = impls_ffi[get_cdata_type_id(obj)]
else
impl = impls_ud.userdata(impls_ffi, obj)
end
return assert(impl, expected_err)
end
end
return impls_ffi.check
end
local function obj_register_interface(if_name, obj_name)
-- loopkup cdata id
local obj_mt = _priv[obj_name]
local obj_type_id = _ctype_meta_map[obj_mt]
local impl_meths = {}
local ffi_impls = _obj_interfaces_ffi[if_name]
ffi_impls[obj_type_id] = impl_meths
_meth[obj_name]['NOBJ_get_' .. if_name] = impl_meths
return impl_meths
end
]==]
local ffi_submodule_template = ffi_module_template
-- re-map meta-methods.
local lua_meta_methods = {
__str__ = '__tostring',
__eq__ = '__eq',
delete = '__gc',
-- Lua metamethods
__add = '__add',
__sub = '__sub',
__mul = '__mul',
__div = '__div',
__mod = '__mod',
__pow = '__pow',
__unm = '__unm',
__len = '__len',
__concat = '__concat',
__eq = '__eq',
__lt = '__lt',
__le = '__le',
__gc = '__gc',
__tostring = '__tostring',
__index = '__index',
__newindex = '__newindex',
}
local MAX_C_LITERAL = (16 * 1024)
local function dump_lua_code_to_c_str(code, name)
-- make Lua code C-safe
code = code:gsub('[\n"\\%z]', {
['\n'] = "\\n\"\n\"",
['\r'] = "\\r",
['"'] = [[\"]],
['\\'] = [[\\]],
['\0'] = [[\0]],
})
local tcode = {'\nstatic const char *', name, '[] = { "', }
-- find all cut positions.
local last_pos = 1
local next_boundry = last_pos + MAX_C_LITERAL
local cuts = {} -- list of positions to cut the code at.
for pos in code:gmatch("()\n") do -- find end position of all lines.
-- check if current line will cross a cut boundry.
if pos > next_boundry then
-- cut code at end of last line.
cuts[#cuts + 1] = last_pos
next_boundry = pos + MAX_C_LITERAL
end
-- track end of last line.
last_pos = pos
end
cuts[#cuts + 1] = last_pos
-- split Lua code into multiple pieces if it is too long.
last_pos = 1
for i=1,#cuts do
local pos = cuts[i]
local piece = code:sub(last_pos, pos-1)
last_pos = pos
if(i > 1) then
-- cut last piece.
tcode[#tcode + 1] = ", /* ----- CUT ----- */"
end
tcode[#tcode + 1] = piece
end
tcode[#tcode + 1] = ', NULL };'
return tcode
end
local function gen_if_defs_code(rec)
if rec.ffi_if_defs then return end
-- generate if code for if_defs.
local if_defs = rec.if_defs
local endif = 'end\n'
if if_defs then
if_defs = "if (" .. rec.obj_table .. rec.ffi_reg_name .. ') then\n'
else
if_defs = ''
endif = ''
end
rec.ffi_if_defs = if_defs
rec.ffi_endif = endif
end
local function reg_object_function(self, func, object)
local ffi_table = '_meth'
local name = func.name
local reg_list
-- check if this is object free/destructure method
if func.is_destructor then
if func._is_hidden then
-- don't register '__gc' metamethods as a public object method.
return '_priv.${object_name}.', '_priv', '__gc'
end
elseif func.is_constructor then
ffi_table = '_pub'
elseif func._is_meta_method then
ffi_table = '_priv'
-- use Lua's __* metamethod names
name = lua_meta_methods[func.name]
elseif func._is_method then
ffi_table = '_meth'
else
ffi_table = '_pub'
end
local obj_table = ffi_table .. '.${object_name}.'
if object._rec_type == 'c_module' then
obj_table = '_M.'
end
return obj_table, ffi_table, name
end
local function add_source(rec, part, src, pos)
return rec:insert_record(c_source(part)(src), 1)
end
print"============ Lua bindings ================="
-- do some pre-processing of objects.
process_records{
object = function(self, rec, parent)
if rec.is_package then return end
local ud_type = rec.userdata_type
if not rec.no_weak_ref then
ud_type = ud_type .. '_weak'
end
rec.ud_type = ud_type
-- create _ffi_check_fast function
rec._ffi_check_fast = ffi_obj_type_check[ud_type]
end,
}
local parsed = process_records{
_interfaces_out = {},
_modules_out = {},
_includes = {},
-- record handlers
c_module = function(self, rec, parent)
local module_c_name = rec.name:gsub('(%.)','_')
rec:add_var('module_c_name', module_c_name)
rec:add_var('module_name', rec.name)
rec:add_var('object_name', rec.name)
self._cur_module = rec
self._modules_out[rec.name] = rec
add_source(rec, "typedefs", ffi_helper_types, 1)
-- hide_meta_info?
if rec.hide_meta_info == nil then rec.hide_meta_info = true end
-- luajit_ffi?
rec:insert_record(define("LUAJIT_FFI")(rec.luajit_ffi and 1 or 0), 1)
-- module_globals?
rec:write_part("ffi_obj_type",
{'REG_MODULES_AS_GLOBALS = ',(rec.module_globals and 'true' or 'false'),'\n'})
-- use_globals?
rec:write_part("ffi_obj_type",
{'REG_OBJECTS_AS_GLOBALS = ',(rec.use_globals and 'true' or 'false'),'\n'})
-- luajit_ffi_load_cmodule?
if rec.luajit_ffi_load_cmodule then
local global = 'false'
if rec.luajit_ffi_load_cmodule == 'global' then
global = 'true'
end
rec:write_part("ffi_typedef", {[[
local Cmod = ffi_load_cmodule("${module_c_name}", ]], global ,[[)
local C = Cmod
]]})
end
-- where we want the module function registered.
rec.functions_regs = 'function_regs'
rec.methods_regs = 'function_regs'
-- symbols to export to FFI
rec:write_part("ffi_export", {
'#if LUAJIT_FFI\n',
'static const ffi_export_symbol ${module_c_name}_ffi_export[] = {\n'})
-- start two ffi.cdef code blocks (one for typedefs and one for function prototypes).
rec:write_part("ffi_typedef", {
'ffi.cdef[[\n'
})
rec:write_part("ffi_cdef", {
'ffi.cdef[[\n'
})
-- add module's FFI template
rec:write_part("ffi_obj_type", {
ffi_module_template,
'\n'
})
end,
c_module_end = function(self, rec, parent)