Debian Codegraph @

texk/web2c/luatexdir/luaffi/test.lua

raw symbols SCIP
1 -- vim: ts=4 sw=4 sts=4 et tw=78
2 -- Portions copyright (c) 2015-present, Facebook, Inc. All rights reserved.
3 -- Portions copyright (c) 2011 James R. McKaskill.
4 --
5 -- This source code is licensed under the BSD-style license found in the
6 -- LICENSE file in the root directory of this source tree. An additional grant
7 -- of patent rights can be found in the PATENTS file in the same directory.
8 --
9 io.stdout:setvbuf('no')
10 local ffi = require 'ffi'
11 local dlls = {}
12 local function loadlib(lib)
13 for pattern in package.cpath:gmatch('[^;]+') do
14 local path = pattern:gsub('?', lib)
15 local ok, lib = pcall(ffi.load, path)
16 if ok then
17 return lib
18 end
19 end
20 error("Unable to load", lib)
21 end
22
23 if _VERSION == 'Lua 5.1' then
24 dlls.__cdecl = loadlib('ffi_test/libtest')
25 else
26 dlls.__cdecl = ffi.load(package.searchpath('ffi_test.libtest', package.cpath))
27 end
28
29 if ffi.arch == 'x86' and ffi.os == 'Windows' then
30 dlls.__stdcall = ffi.load('test_stdcall')
31 dlls.__fastcall = ffi.load('test_fastcall')
32 end
33
34 local function check(a, b, msg)
35 if a ~= b then
36 print('check', a, b)
37 end
38 return _G.assert(a == b, msg)
39 end
40
41 print('Running test')
42
43 ffi.cdef [[
44 enum e8 {
45 FOO8,
46 BAR8,
47 };
48 enum e16 {
49 FOO16 = 1 << 8,
50 BAR16,
51 BIG16 = 1 << 14,
52 };
53 enum e32 {
54 FOO32 = 1 << 16,
55 BAR32,
56 BIG32 = 1 << 30,
57 };
58 int max_alignment();
59 bool is_msvc, is_msvc2 __asm__("is_msvc");
60 bool have_complex(void);
61 bool have_complex2() __asm__("have" /*foo*/ "\x5F" "complex"); // 5F is _
62
63 int8_t add_i8(int8_t a, int8_t b);
64 uint8_t add_u8(uint8_t a, uint8_t b);
65 int16_t add_i16(int16_t a, int16_t b);
66 uint16_t add_u16(uint16_t a, uint16_t b);
67 int32_t add_i32(int32_t a, int32_t b);
68 uint32_t add_u32(uint32_t a, uint32_t b);
69 int64_t add_i64(int64_t a, int64_t b);
70 uint64_t add_u64(uint64_t a, uint64_t b);
71 double add_d(double a, double b);
72 float add_f(float a, float b);
73 double complex add_dc(double complex a, double complex b);
74 float complex add_fc(float complex a, float complex b);
75 enum e8 inc_e8(enum e8);
76 enum e16 inc_e16(enum e16);
77 enum e32 inc_e32(enum e32);
78 bool not_b(bool v);
79 _Bool not_b2(_Bool v);
80 typedef bool (*fp)(bool);
81 fp ret_fp(fp v);
82 bool (*ret_fp2(bool (*)(bool)))(bool) __asm("ret_fp");
83
84 int print_i8(char* buf, int8_t val);
85 int print_u8(char* buf, uint8_t val);
86 int print_i16(char* buf, int16_t val);
87 int print_u16(char* buf, uint16_t val);
88 int print_i32(char* buf, int32_t val);
89 int print_u32(char* buf, uint32_t val);
90 int print_i64(char* buf, int64_t val);
91 int print_u64(char* buf, uint64_t val);
92 int print_s(char* buf, const char* val);
93 int print_b(char* buf, bool val);
94 int print_b2(char* buf, _Bool val);
95 int print_d(char* buf, double val);
96 int print_f(char* buf, float val);
97 int print_p(char* buf, void* val);
98 int print_dc(char* buf, double complex val);
99 int print_fc(char* buf, float complex val);
100 int print_e8(char* buf, enum e8 val);
101 int print_e16(char* buf, enum e16 val);
102 int print_e32(char* buf, enum e32 val);
103 int sprintf(char* buf, const char* format, ...);
104
105 // Examples from MSDN
106
107 // bit_fields1.cpp
108 // compile with: /LD
109 struct Date {
110 unsigned short nWeekDay : 3; // 0..7 (3 bits)
111 unsigned short nMonthDay : 6; // 0..31 (6 bits)
112 unsigned short nMonth : 5; // 0..12 (5 bits)
113 unsigned short nYear : 8; // 0..100 (8 bits)
114 };
115
116 // bit_fields2.cpp
117 // compile with: /LD
118 struct Date2 {
119 unsigned nWeekDay : 3; // 0..7 (3 bits)
120 unsigned nMonthDay : 6; // 0..31 (6 bits)
121 unsigned : 0; // Force alignment to next boundary.
122 unsigned nMonth : 5; // 0..12 (5 bits)
123 unsigned nYear : 8; // 0..100 (8 bits)
124 };
125
126 // For checking the alignment of short bitfields
127 struct Date3 {
128 char pad;
129 unsigned short nWeekDay : 3; // 0..7 (3 bits)
130 unsigned short nMonthDay : 6; // 0..31 (6 bits)
131 unsigned short nMonth : 5; // 0..12 (5 bits)
132 unsigned short nYear : 8; // 0..100 (8 bits)
133 };
134
135 // For checking the alignment and container of int64 bitfields
136 struct bit64 {
137 char pad;
138 uint64_t a : 15;
139 uint64_t b : 14;
140 uint64_t c : 13;
141 uint64_t d : 12;
142 };
143
144 // Examples from SysV X86 ABI
145 struct sysv1 {
146 int j:5;
147 int k:6;
148 int m:7;
149 };
150
151 struct sysv2 {
152 short s:9;
153 int j:9;
154 char c;
155 short t:9;
156 short u:9;
157 char d;
158 };
159
160 struct sysv3 {
161 char c;
162 short s:8;
163 };
164
165 union sysv4 {
166 char c;
167 short s:8;
168 };
169
170 struct sysv5 {
171 char c;
172 int :0;
173 char d;
174 short :9;
175 char e;
176 char :0;
177 };
178
179 struct sysv6 {
180 char c;
181 int :0;
182 char d;
183 int :9;
184 char e;
185 };
186
187 struct sysv7 {
188 int j:9;
189 short s:9;
190 char c;
191 short t:9;
192 short u:9;
193 };
194
195 int print_date(size_t* sz, size_t* align, char* buf, struct Date* s);
196 int print_date2(size_t* sz, size_t* align, char* buf, struct Date2* s);
197 int print_date3(size_t* sz, size_t* align, char* buf, struct Date3* d);
198 int print_bit64(size_t* sz, size_t* align, char* buf, struct bit64* d);
199 int print_sysv1(size_t* sz, size_t* align, char* buf, struct sysv1* s);
200 int print_sysv2(size_t* sz, size_t* align, char* buf, struct sysv2* s);
201 int print_sysv3(size_t* sz, size_t* align, char* buf, struct sysv3* s);
202 int print_sysv4(size_t* sz, size_t* align, char* buf, union sysv4* s);
203 int print_sysv5(size_t* sz, size_t* align, char* buf, struct sysv5* s);
204 int print_sysv6(size_t* sz, size_t* align, char* buf, struct sysv6* s);
205 int print_sysv7(size_t* sz, size_t* align, char* buf, struct sysv7* s);
206
207 struct fptr {
208 int (__cdecl *p)(int);
209 };
210 int call_fptr(struct fptr* s, int val);
211
212 bool g_b;
213 int8_t g_i8;
214 int16_t g_i16;
215 int32_t g_i32;
216 int64_t g_i64;
217 uint8_t g_u8;
218 uint16_t g_u16;
219 uint32_t g_u32;
220 uint64_t g_u64;
221 float g_f;
222 double g_d;
223 double complex g_dc;
224 float complex g_fc;
225 bool (*g_fp)(bool);
226 const char g_s[];
227 const char* g_sp;
228 void* g_p;
229 enum e8 g_e8;
230 enum e16 g_e16;
231 enum e32 g_e32;
232 struct Date g_date;
233
234 void set_errno(int val);
235 int get_errno(void);
236 ]]
237
238 local align = [[
239 struct align_ALIGN_SUFFIX {
240 char pad;
241 TYPE v;
242 };
243
244 int print_align_ALIGN_SUFFIX(char* buf, struct align_ALIGN_SUFFIX* p);
245 ]]
246
247 local palign = [[
248 #pragma pack(push)
249 #pragma pack(ALIGN)
250 ]] .. align .. [[
251 #pragma pack(pop)
252 ]]
253
254 local bitfields = [[
255 struct bcTNUM {
256 uintTNUM_t a : 3;
257 intTNUM_t b : 3;
258 };
259 struct blzTNUM {
260 uintTNUM_t a;
261 uintTNUM_t :0;
262 uintTNUM_t b;
263 };
264 int print_bcTNUM(size_t* sz, size_t* align, char* buf, struct bcTNUM* s);
265 int print_blzTNUM(size_t* sz, size_t* align, char* buf, struct blzTNUM* s);
266 ]]
267
268 local bitalign = [[
269 struct ba_TNUM_BNUM {
270 char a;
271 uintTNUM_t b : BNUM;
272 };
273 struct bu_TNUM_BNUM {
274 char a;
275 uintTNUM_t :BNUM;
276 char b;
277 };
278 int print_ba_TNUM_BNUM(size_t* sz, size_t* align, char* buf, struct ba_TNUM_BNUM* s);
279 ]]
280
281 local bitzero = [[
282 struct bz_TNUM_ZNUM_BNUM {
283 uint8_t a;
284 uintTNUM_t b : 3;
285 uintZNUM_t :BNUM;
286 uintTNUM_t c : 3;
287 };
288 int print_bz_TNUM_ZNUM_BNUM(size_t* sz, size_t* align, char* buf, struct bz_TNUM_ZNUM_BNUM* s);
289 ]]
290
291 local i = ffi.C.i
292 local test_values = {
293 ['void*'] = ffi.new('char[3]'),
294 ['const char*'] = 'foo',
295 float = 3.4,
296 double = 5.6,
297 uint16_t = 65000,
298 uint32_t = ffi.new('uint32_t', 700000056),
299 uint64_t = 12345678901234,
300 bool = true,
301 _Bool = false,
302 ['float complex'] = 3.1+4.2*i,
303 ['double complex'] = 5.1+6.2*i,
304 ['enum e8'] = ffi.C.FOO8,
305 ['enum e16'] = ffi.C.FOO16,
306 ['enum e32'] = ffi.C.FOO32,
307 }
308
309 local types = {
310 b = 'bool',
311 b2 = '_Bool',
312 d = 'double',
313 f = 'float',
314 u64 = 'uint64_t',
315 u32 = 'uint32_t',
316 u16 = 'uint16_t',
317 s = 'const char*',
318 p = 'void*',
319 e8 = 'enum e8',
320 e16 = 'enum e16',
321 e32 = 'enum e32',
322 }
323
324 local buf = ffi.new('char[256]')
325
326 local function checkbuf(type, ret, msg)
327 local str = tostring(test_values[type]):gsub('^cdata%b<>: ', '')
328 check(ffi.string(buf), str, msg)
329 check(ret, #str, msg)
330 end
331
332 local function checkalign(type, v, ret)
333 --print(v)
334 local str = tostring(test_values[type]):gsub('^cdata%b<>: ', '')
335 check(ffi.string(buf), ('size %d offset %d align %d value %s'):format(ffi.sizeof(v), ffi.offsetof(v, 'v'), ffi.alignof(v, 'v'), str))
336 check(ret, #str)
337 end
338
339 local u64 = ffi.typeof('uint64_t')
340 local i64 = ffi.typeof('int64_t')
341
342 local first = true
343
344 for convention,c in pairs(dlls) do
345 check(c.add_i8(1,1), 2)
346 check(c.add_i8(256,1), 1)
347 check(c.add_i8(127,1), -128)
348 check(c.add_i8(-120,120), 0)
349 check(c.add_u8(255,1), 0)
350 check(c.add_u8(120,120), 240)
351 check(c.add_i16(2000,4000), 6000)
352 check(c.add_d(20, 12), 32)
353 check(c.add_f(40, 32), 72)
354 check(c.not_b(true), false)
355 check(c.not_b2(false), true)
356 check(c.inc_e8(c.FOO8), c.BAR8)
357 check(c.inc_e8('FOO8'), c.BAR8)
358 check(c.inc_e16(c.FOO16), c.BAR16)
359 check(c.inc_e32(c.FOO32), c.BAR32)
360 check(c.ret_fp(c.g_fp), c.g_fp)
361 check(c.ret_fp2(c.g_fp), c.g_fp)
362
363 if c.have_complex() then
364 check(c.add_dc(3+4*i, 4+5*i), 7+9*i)
365 check(c.add_fc(2+4*i, 6+8*i), 8+12*i)
366 types.dc = 'double complex'
367 types.fc = 'float complex'
368 else
369 types.dc = nil
370 types.fc = nil
371 end
372 check((3+4*i).re, 3)
373 check((3+4*i).im, 4)
374 check(ffi.new('complex float', 2+8*i).re, 2)
375 check(ffi.new('complex float', 5+6*i).im, 6)
376
377 check(c.have_complex(), c.have_complex2())
378 check(c.is_msvc, c.is_msvc2)
379
380 check(c.g_b, true)
381 check(c.g_i8, -8)
382 check(c.g_i16, -16)
383 check(c.g_i32, -32)
384 check(c.g_i64, i64(-64))
385 check(c.g_u8, 8)
386 check(c.g_u16, 16)
387 check(c.g_u32, 32)
388 check(c.g_u64, u64(64))
389 check(c.g_f, 3)
390 check(c.g_d, 5)
391 if c.have_complex() then
392 check(c.g_dc, 7 + 8*i)
393 check(c.g_fc, 6 + 9*i)
394 end
395 check(ffi.cast('void*', c.g_fp), c.g_p)
396 check(c.g_s, 'g_s')
397 check(c.g_sp, 'g_sp')
398 check(c.g_e8, c.FOO8)
399 check(c.g_e16, c.FOO16)
400 check(c.g_e32, c.FOO32)
401 check(c.g_date.nWeekDay, 1)
402 check(c.g_date.nMonthDay, 2)
403 check(c.g_date.nMonth, 3)
404 check(c.g_date.nYear, 4)
405
406 c.g_b = false; check(c.g_b, false)
407 c.g_i8 = -108; check(c.g_i8, -108)
408 c.g_i16 = -1016; check(c.g_i16, -1016)
409 c.g_i32 = -1032; check(c.g_i32, -1032)
410 c.g_i64 = -1064; check(c.g_i64, i64(-1064))
411 c.g_u8 = 208; check(c.g_u8, 208)
412 c.g_u16 = 2016; check(c.g_u16, 2016)
413 c.g_u32 = 2032; check(c.g_u32, 2032)
414 c.g_u64 = 2064; check(c.g_u64, u64(2064))
415 c.g_f = 13; check(c.g_f, 13)
416 c.g_d = 15; check(c.g_d, 15)
417 if c.have_complex() then
418 c.g_dc = 17+18*i; check(c.g_dc, 17+18*i)
419 c.g_fc = 16+19*i; check(c.g_fc, 16+19*i)
420 end
421 c.g_sp = 'foo'; check(c.g_sp, 'foo')
422 c.g_e8 = c.BAR8; check(c.g_e8, c.BAR8)
423 c.g_e16 = c.BAR16; check(c.g_e16, c.BAR16)
424 c.g_e32 = c.BAR32; check(c.g_e32, c.BAR32)
425 c.g_date.nWeekDay = 3; check(c.g_date.nWeekDay, 3)
426
427 local align_attr = c.is_msvc and [[
428 struct align_attr_ALIGN_SUFFIX {
429 char pad;
430 __declspec(align(ALIGN)) TYPE v;
431 };
432
433 int print_align_attr_ALIGN_SUFFIX(char* buf, struct align_attr_ALIGN_SUFFIX* p);
434 ]] or [[
435 struct align_attr_ALIGN_SUFFIX {
436 char pad;
437 TYPE v __attribute__(aligned(ALIGN));
438 };
439
440 int print_align_attr_ALIGN_SUFFIX(char* buf, struct align_attr_ALIGN_SUFFIX* p);
441 ]]
442
443 for suffix, type in pairs(types) do
444 local test = test_values[type]
445 --print('checkbuf', suffix, type, buf, test)
446 checkbuf(type, c['print_' .. suffix](buf, test), suffix)
447
448 if first then
449 ffi.cdef(align:gsub('SUFFIX', suffix):gsub('TYPE', type):gsub('ALIGN', 0))
450 end
451
452 local v = ffi.new('struct align_0_' .. suffix, {0, test})
453 checkalign(type, v, c['print_align_0_' .. suffix](buf, v))
454
455 for _,align in ipairs{1,2,4,8,16} do
456 if align > c.max_alignment() then
457 break
458 end
459
460 if first then
461 ffi.cdef(palign:gsub('SUFFIX', suffix):gsub('TYPE', type):gsub('ALIGN', align))
462 ffi.cdef(align_attr:gsub('SUFFIX', suffix):gsub('TYPE', type):gsub('ALIGN', align))
463 end
464
465 local v = ffi.new('struct align_' .. align .. '_' .. suffix, {0, test})
466 checkalign(type, v, c['print_align_' .. align .. '_' .. suffix](buf, v))
467
468 -- MSVC doesn't support aligned attributes on enums
469 if not type:match('^enum e[0-9]*$') or not c.is_msvc then
470 local v2 = ffi.new('struct align_attr_' .. align .. '_' .. suffix, {0, test})
471 checkalign(type, v2, c['print_align_attr_' .. align .. '_' .. suffix](buf, v2))
472 end
473 end
474
475 if not c.is_msvc then
476 if first then
477 local h = [[
478 struct align_attr_def_SUFFIX {
479 char pad;
480 TYPE v __attribute__(aligned);
481 };
482 int print_align_attr_def_SUFFIX(char* buf, struct align_attr_def_SUFFIX* p);
483 ]]
484 ffi.cdef(h:gsub('SUFFIX', suffix):gsub('TYPE', type))
485 end
486
487 local v = ffi.new('struct align_attr_def_' .. suffix, {0, test})
488 -- print(type)
489 -- print("Align " .. c['print_align_attr_def_' .. suffix](buf, v))
490 -- print(ffi.string(buf))
491 -- checkalign(type, v, c['print_align_attr_def_' .. suffix](buf, v))
492 end
493 end
494
495 local psz = ffi.new('size_t[1]')
496 local palign = ffi.new('size_t[1]')
497 local function check_align(type, test, ret)
498 --print('check_align', type, test, ret, ffi.string(buf), psz[0], palign[0])
499 check(tonumber(palign[0]), ffi.alignof(type))
500 check(tonumber(psz[0]), ffi.sizeof(type))
501 check(ret, #test)
502 check(test, ffi.string(buf))
503 end
504
505 for _, tnum in ipairs{8, 16, 32, 64} do
506 if first then
507 ffi.cdef(bitfields:gsub('TNUM',tnum))
508 end
509
510 check_align('struct bc'..tnum, '1 2', c['print_bc'..tnum](psz, palign, buf, {1,2}))
511 check_align('struct blz'..tnum, '1 2', c['print_blz'..tnum](psz, palign, buf, {1,2}))
512
513 for _, znum in ipairs{8, 16, 32, 64} do
514 for _, bnum in ipairs{7, 15, 31, 63} do
515 if bnum > znum then
516 break
517 end
518 if first then
519 ffi.cdef(bitzero:gsub('TNUM',tnum):gsub('ZNUM',znum):gsub('BNUM', bnum))
520 end
521 check_align('struct bz_'..tnum..'_'..znum..'_'..bnum, '1 2 3', c['print_bz_'..tnum..'_'..znum..'_'..bnum](psz, palign, buf, {1,2,3}))
522 end
523 end
524
525 for _, bnum in ipairs{7, 15, 31, 63} do
526 if bnum > tnum then
527 break
528 end
529 if first then
530 ffi.cdef(bitalign:gsub('TNUM',tnum):gsub('BNUM',bnum))
531 end
532 check_align('struct ba_'..tnum..'_'..bnum, '1 2', c['print_ba_'..tnum..'_'..bnum](psz, palign, buf, {1,2}))
533 end
534 end
535
536 check_align('struct Date', '1 2 3 4', c.print_date(psz, palign, buf, {1,2,3,4}))
537 check_align('struct Date2', '1 2 3 4', c.print_date2(psz, palign, buf, {1,2,3,4}))
538 check_align('struct sysv1', '1 2 3', c.print_sysv1(psz, palign, buf, {1,2,3}))
539 check_align('struct sysv2', '1 2 3 4 5 6', c.print_sysv2(psz, palign, buf, {1,2,3,4,5,6}))
540 check_align('struct sysv3', '1 2', c.print_sysv3(psz, palign, buf, {1,2}))
541 check_align('union sysv4', '1', c.print_sysv4(psz, palign, buf, {1}))
542 check_align('struct sysv5', '1 2 3', c.print_sysv5(psz, palign, buf, {1,2,3}))
543 check_align('struct sysv6', '1 2 3', c.print_sysv6(psz, palign, buf, {1,2,3}))
544 check_align('struct sysv7', '1 2 3 4 5', c.print_sysv7(psz, palign, buf, {1,2,3,4,5}))
545
546 local cbs = [[
547 typedef const char* (*__cdecl sfunc)(const char*);
548 int call_i(int (*__cdecl func)(int), int arg);
549 float call_f(float (*__cdecl func)(float), float arg);
550 double call_d(double (*__cdecl func)(double), double arg);
551 const char* call_s(sfunc func, const char* arg);
552 _Bool call_b(_Bool (*__cdecl func)(_Bool), _Bool arg);
553 double complex call_dc(double complex (*__cdecl func)(double complex), double complex arg);
554 float complex call_fc(float complex (*__cdecl func)(float complex), float complex arg);
555 enum e8 call_e8(enum e8 (*__cdecl func)(enum e8), enum e8 arg);
556 enum e16 call_e16(enum e16 (*__cdecl func)(enum e16), enum e16 arg);
557 enum e32 call_e32(enum e32 (*__cdecl func)(enum e32), enum e32 arg);
558 ]]
559
560 ffi.cdef(cbs:gsub('__cdecl', convention))
561
562 local u3 = ffi.new('uint64_t', 3)
563 check(c.call_i(function(a) return 2*a end, 3), 6)
564 assert(math.abs(c.call_d(function(a) return 2*a end, 3.2) - 6.4) < 0.0000000001)
565 assert(math.abs(c.call_f(function(a) return 2*a end, 3.2) - 6.4) < 0.000001)
566 check(ffi.string(c.call_s(function(s) return s + u3 end, 'foobar')), 'bar')
567 check(c.call_b(function(v) return not v end, true), false)
568 check(c.call_e8(function(v) return v + 1 end, c.FOO8), c.BAR8)
569 check(c.call_e16(function(v) return v + 1 end, c.FOO16), c.BAR16)
570 check(c.call_e32(function(v) return v + 1 end, c.FOO32), c.BAR32)
571
572 if c.have_complex() then
573 check(c.call_dc(function(v) return v + 2+3*i end, 4+6*i), 6+9*i)
574 check(c.call_fc(function(v) return v + 1+2*i end, 7+4*i), 8+6*i)
575 end
576
577 local u2 = ffi.new('uint64_t', 2)
578 local cb = ffi.new('sfunc', function(s) return s + u3 end)
579 check(ffi.string(cb('foobar')), 'bar')
580 check(ffi.string(c.call_s(cb, 'foobar')), 'bar')
581 cb:set(function(s) return s + u2 end)
582 check(ffi.string(c.call_s(cb, 'foobar')), 'obar')
583
584 local fp = ffi.new('struct fptr')
585 assert(fp.p == ffi.C.NULL)
586 fp.p = function(a) return 2*a end
587 assert(fp.p ~= ffi.C.NULL)
588 check(c.call_fptr(fp, 4), 8)
589 local suc, err = pcall(function() fp.p:set(function() end) end)
590 assert(not suc)
591 check(err:gsub('^.*: ',''), "can't set the function for a non-lua callback")
592
593 check(c.call_fptr({function(a) return 3*a end}, 5), 15)
594
595 local suc, err = pcall(c.call_s, function(s) error(ffi.string(s), 0) end, 'my error')
596 check(suc, false)
597 check(err, 'my error')
598
599 check(ffi.errno(), c.get_errno())
600 c.set_errno(3)
601 check(ffi.errno(), 3)
602 check(c.get_errno(), 3)
603 check(ffi.errno(4), 3)
604 check(ffi.errno(), 4)
605 check(c.get_errno(), 4)
606
607 local gccattr = {
608 __cdecl = 'int test_pow(int v) __attribute__((cdecl));',
609 __stdcall = 'int test_pow(int v) __attribute__(stdcall);',
610 __fastcall = '__attribute__(fastcall) int test_pow(int v);',
611 }
612
613 ffi.cdef(gccattr[convention])
614 check(c.test_pow(5), 25)
615
616 ffi.cdef [[
617 int va_list_size, va_list_align;
618 int vsnprintf(char* buf, size_t sz, const char* fmt, va_list ap);
619 ]]
620 ffi.new('va_list')
621 assert(ffi.debug().functions.vsnprintf ~= nil)
622 assert(ffi.istype('va_list', ffi.new('__builtin_va_list')))
623 assert(ffi.istype('va_list', ffi.new('__gnuc_va_list')))
624 check(ffi.sizeof('va_list'), c.va_list_size)
625 check(ffi.alignof('va_list'), c.va_list_align)
626
627 first = false
628 end
629
630 local c = ffi.C
631
632 assert(c.sprintf(buf, "%g", 5.3) == 3 and ffi.string(buf) == '5.3')
633 assert(c.sprintf(buf, "%d", false) == 1 and ffi.string(buf) == '0')
634 assert(c.sprintf(buf, "%d%g", false, 6.7) == 4 and ffi.string(buf) == '06.7')
635
636 do
637 local i = 'C';
638 local j = ffi.cast("char", 67);
639 local k = ffi.cast("int16_t", 16);
640 local l = ffi.cast("int", 20);
641 local m = ffi.cast("int64_t", 25);
642 assert(c.sprintf(buf, "%s %c %hd %d %lld", i, j, k, l, m) == 12 and ffi.string(buf) == 'C C 16 20 25')
643 end
644
645 assert(ffi.sizeof('uint32_t[?]', 32) == 32 * 4)
646 assert(ffi.sizeof(ffi.new('uint32_t[?]', 32)) == 32 * 4)
647
648 ffi.cdef [[
649 struct vls {
650 struct {
651 char a;
652 struct {
653 char b;
654 char v[?];
655 } c;
656 } d;
657 };
658 struct vls2 {
659 char pad;
660 union {
661 uint8_t a;
662 uint16_t b;
663 };
664 };
665 ]]
666
667 assert(ffi.sizeof('struct vls', 3) == 5)
668 assert(ffi.sizeof(ffi.new('struct vls', 4).d.c) == 5)
669 assert(ffi.offsetof('struct vls2', 'a') == 2)
670 assert(ffi.sizeof('struct vls2') == 4)
671
672 ffi.cdef [[ static const int DUMMY = 8 << 2; ]]
673 assert(ffi.C.DUMMY == 32)
674
675 ffi.new('struct {const char* foo;}', {'foo'})
676
677 assert(not pcall(function()
678 ffi.new('struct {char* foo;}', {'ff'})
679 end))
680
681 local mt = {}
682 local vls = ffi.new(ffi.metatype('struct vls', mt), 1)
683
684 assert(not pcall(function() return vls.key end))
685
686 mt.__index = function(vls, key)
687 return function(vls, a, b)
688 return 'in index ' .. key .. ' ' .. vls.d.a .. ' ' .. a .. ' ' .. b
689 end
690 end
691
692 vls.d.a = 3
693 check(vls:key('a', 'b'), 'in index key 3 a b')
694
695 assert(not pcall(function() vls.k = 3 end))
696
697 mt.__newindex = function(vls, key, val)
698 error('in newindex ' .. key .. ' ' .. vls.d.a .. ' ' .. val, 0)
699 end
700
701 vls.d.a = 4
702 local suc, err = pcall(function() vls.key = 'val' end)
703 assert(not suc)
704 check(err, 'in newindex key 4 val')
705
706 mt.__add = function(vls, a) return vls.d.a + a end
707 mt.__sub = function(vls, a) return vls.d.a - a end
708 mt.__mul = function(vls, a) return vls.d.a * a end
709 mt.__div = function(vls, a) return vls.d.a / a end
710 mt.__mod = function(vls, a) return vls.d.a % a end
711 mt.__pow = function(vls, a) return vls.d.a ^ a end
712 mt.__eq = function(vls, a) return u64(vls.d.a) == a end
713 mt.__lt = function(vls, a) return u64(vls.d.a) < a end
714 mt.__le = function(vls, a) return u64(vls.d.a) <= a end
715 mt.__call = function(vls, a, b) return '__call', vls.d.a .. a .. (b or 'nil') end
716 mt.__unm = function(vls) return -vls.d.a end
717 mt.__concat = function(vls, a) return vls.d.a .. a end
718 mt.__len = function(vls) return vls.d.a end
719 mt.__tostring = function(vls) return 'string ' .. vls.d.a end
720
721 vls.d.a = 5
722 check(vls + 5, 10)
723 check(vls - 5, 0)
724 check(vls * 5, 25)
725 check(vls / 5, 1)
726 check(vls % 3, 2)
727 check(vls ^ 3, 125)
728 check(vls == u64(4), false)
729 check(vls == u64(5), true)
730 check(vls == u64(6), false)
731 check(vls < u64(4), false)
732 check(vls < u64(5), false)
733 check(vls < u64(6), true)
734 check(vls <= u64(4), false)
735 check(vls <= u64(5), true)
736 check(vls <= u64(6), true)
737 check(-vls, -5)
738 local a,b = vls('6')
739 check(a, '__call')
740 check(b, '56nil')
741 check(tostring(vls), 'string 5')
742
743 if _VERSION ~= 'Lua 5.1' then
744 check(vls .. 'str', '5str')
745 check(#vls, 5)
746 end
747
748 check(tostring(1.1+3.2*i), '1.1+3.2i')
749 check((1+3*i)*(2+4*i), -10+10*i)
750 check((3+2*i)*(3-2*i), 13+0*i)
751
752 -- Should ignore unknown attributes
753 ffi.cdef [[
754 typedef int ALenum;
755 __attribute__((dllimport)) void __attribute__((__cdecl__)) alEnable( ALenum capability );
756 ]]
757
758 check(ffi.sizeof('struct {char foo[alignof(uint64_t)];}'), ffi.alignof('uint64_t'))
759
760 -- Check native number type for int64_t/uint64_t function args/returns in Lua 5.3
761 if _VERSION == "Lua 5.3" then
762 local native_7F = 0x7FFFFFFFFFFFFFFF
763 local cdata_long_7F = ffi.new("int64_t", 0x7FFFFFFFFFFFFFFF)
764 local cdata_ulong_7F = ffi.new("uint64_t", 0x7FFFFFFFFFFFFFFF)
765
766 local native_80 = 0x8000000000000000
767 for _, func in ipairs{ffi.C.add_i64, ffi.C.add_u64} do
768 -- 0x7FFFFFFFFFFFFFFF (native) + 1 == 0x8000000000000000 (native)
769 local res = func(native_7F, 1)
770 assert(type(res) == "number", "native_7F: returned value not a number")
771 assert(res == native_80, "native_7F: math error")
772
773 -- 0x7FFFFFFFFFFFFFFF (cdata int64_t) + 1 == 0x8000000000000000 (native)
774 local res = func(cdata_long_7F, 1)
775 assert(type(res) == "number", "cdata_long_7F: returned value not a number")
776 assert(res == native_80, "cdata_long_7F: math error")
777
778 -- 0x7FFFFFFFFFFFFFFF (cdata uint64_t) + 1 == 0x8000000000000000 (native)
779 local res = func(cdata_ulong_7F, 1)
780 assert(type(res) == "number", "cdata_ulong_7F: returned value not a number")
781 assert(res == native_80, "cdata_ulong_7F: math error")
782 end
783 end
784
785 -- Long double is not supported yet but it should be parsed
786 ffi.cdef('long double foo(long double val);')
787 check(tostring(ffi.debug().functions.foo):match('ctype(%b<>)'), '<long double (*)(long double)>')
788
789 ffi.cdef [[
790 typedef int byte1 __attribute__(mode(QI));
791 typedef int byte2 __attribute__(mode(HI));
792 typedef int byte4 __attribute__(mode(SI));
793 typedef int byte8 __attribute__(mode(DI));
794 typedef unsigned ubyte8 __attribute__(mode(DI));
795 typedef int word __attribute__(mode(word));
796 typedef int pointer __attribute__(mode(pointer));
797 typedef int byte __attribute__(mode(byte));
798 typedef float float4 __attribute__(mode(SF));
799 typedef float float8 __attribute__(mode(DF));
800 ]]
801 assert(ffi.istype('int8_t', ffi.new('byte1')))
802 assert(ffi.istype('int16_t', ffi.new('byte2')))
803 assert(ffi.istype('int32_t', ffi.new('byte4')))
804 assert(ffi.istype('int64_t', ffi.new('byte8')))
805 assert(ffi.istype('uint64_t', ffi.new('ubyte8')))
806 check(ffi.sizeof('void*'), ffi.sizeof('pointer'))
807 check(ffi.alignof('void*'), ffi.alignof('pointer'))
808 check(ffi.sizeof('void*'), ffi.sizeof('word'))
809 check(ffi.alignof('void*'), ffi.alignof('word'))
810 assert(ffi.istype('int8_t', ffi.new('byte')))
811 assert(ffi.istype('float', ffi.new('float4')))
812 assert(ffi.istype('double', ffi.new('float8')))
813
814 ffi.cdef('void register_foo(register int val);')
815 check(tostring(ffi.debug().functions.register_foo):match('%b<>'), '<void (*)(int)>')
816
817 ffi.cdef [[
818 typedef struct __sFILE FILE;
819 ]]
820
821 assert(not ffi.istype('int', ffi.new('int*')))
822 assert(not ffi.istype('int[]', ffi.new('int*')))
823 assert(not ffi.istype('int[3]', ffi.new('int*')))
824 assert(not ffi.istype('int[3]', ffi.new('int[2]')))
825 assert(ffi.istype('const int[3]', ffi.new('const int[3]')))
826 assert(ffi.istype('int[3]', ffi.new('const int[3]')))
827
828 -- Crazy function pointer that takes an int and a function pointer and returns
829 -- a function pointer. Type of &signal.
830 check(tostring(ffi.typeof('void (*foo(int, void(*)(int)))(int)')):match('%b<>'), '<void (*(*)(int, void (*)(int)))(int)>')
831
832 -- Make sure we pass all arguments to tonumber
833 check(tonumber('FE', 16), 0xFE)
834
835 -- Allow casts from pointer to numeric types
836 ffi.cast('long', ffi.C.NULL)
837 ffi.cast('int8_t', ffi.C.NULL)
838 assert(not pcall(function() ffi.new('long', ffi.C.NULL) end))
839
840 -- ffi.new and ffi.cast allow unpacked struct/arrays
841 assert(ffi.new('int[3]', 1)[0] == 1)
842 assert(ffi.new('int[3]', {1})[0] == 1)
843 assert(ffi.new('int[3]', 1, 2)[1] == 2)
844 assert(ffi.new('int[3]', {1, 2})[1] == 2)
845
846 ffi.cdef[[
847 struct var {
848 char ch[?];
849 };
850 ]]
851 local d = ffi.new('char[4]')
852 local v = ffi.cast('struct var*', d)
853 v.ch = {1,2,3,4}
854 assert(v.ch[3] == 4)
855 v.ch = "bar"
856 assert(v.ch[3] == 0)
857 assert(v.ch[2] == string.byte('r'))
858 assert(d[1] == string.byte('a'))
859
860 ffi.cast('char*', 1)
861
862 -- 2 arg form of ffi.copy
863 ffi.copy(d, 'bar')
864
865 -- unsigned should be ignored for pointer rules
866 ffi.cdef[[
867 int strncmp(const signed char *s1, const unsigned char *s2, size_t n);
868 ]]
869 assert(ffi.C.strncmp("two", "three", 3) ~= 0)
870
871 ffi.fill(d, 3, 1)
872 assert(d[2] == 1)
873 ffi.fill(d, 3)
874 assert(d[2] == 0)
875
876 -- tests for __new
877 ffi.cdef[[
878 struct newtest {
879 int a;
880 int b;
881 int c;
882 };
883 struct newtest_1 {
884 int a;
885 int b;
886 int c;
887 };
888 struct newtest_2 {
889 int a;
890 int b;
891 int c;
892 };
893 ]]
894
895 local tp = ffi.metatype("struct newtest", {__new =
896 function(tp, x, y, z)
897 tp = ffi.new(tp)
898 tp.a, tp.b, tp.c = x, y, z
899 return tp
900 end})
901 local v = tp(1, 2, 3)
902 assert(v.a == 1 and v.b == 2 and v.c == 3)
903
904 local tp = ffi.metatype("struct newtest_1", {__new =
905 function(tp, x, y, z)
906 tp = ffi.new(tp, {a = x, b = y, c = z})
907 return tp
908 end})
909 local v = tp(1, 2, 3)
910 assert(v.a == 1 and v.b == 2 and v.c == 3)
911
912 -- tests for __pairs and __ipairs; not iterating just testing what is returned
913 local tp = ffi.metatype("struct newtest_2",
914 {__pairs = function(tp) return tp.a, tp.b end, __ipairs = function(tp) return tp.b, tp.c end}
915 )
916 if _VERSION ~= 'Lua 5.1' then
917 local v = tp(1, 2, 3)
918 local x, y = pairs(v)
919 assert(x == 1 and y == 2)
920 x, y = ipairs(v)
921 assert(x == 2 and y == 3)
922 end
923
924 -- test for pointer to struct having same metamethods
925 local st = ffi.cdef "struct ptest {int a, b;};"
926 local tp = ffi.metatype("struct ptest", {__index = function(s, k) return k end, __len = function(s) return 3 end})
927
928 local a = tp(1, 2)
929 assert(a.banana == "banana")
930 assert(#a == 3)
931 local b = ffi.new("int[2]")
932 local c = ffi.cast("struct ptest *", b)
933 assert(c.banana == "banana") -- should have same methods
934 assert(#c == 3)
935
936
937 ffi.cdef [[
938 char buf[512];
939 void test_call_echo(const char* c);
940 void test_call_pppppii(void* a, void* b, void* c, void* d, void* e, int f, int g);
941 void test_call_pppppiiiiii(void* p1, void* p2, void* p3, void* p4, void* p5, int i1, int i2, int i3, int i4, int i5, int i6);
942 void test_call_pppppffffff(void* p1, void* p2, void* p3, void* p4, void* p5, float f1, float f2, float f3, float f4, float f5, float f6);
943 void test_call_pppppffffffffff(void* p1, void* p2, void* p3, void* p4, void* p5, float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, float f10);
944 void test_call_pppppiifiii(void* p1, void* p2, void* p3, void* p4, void* p5, int i1, int i2, float f3, int i4, int i5, int i6);
945 void test_call_pppppiiifii(void* p1, void* p2, void* p3, void* p4, void* p5, int i1, int i2, int i3, float i4, int i5, int i6);
946 ]]
947
948 ffi.C.test_call_echo("input")
949 assert(ffi.C.buf == "input")
950
951 local function ptr(x) return ffi.new('void*', x) end
952
953 ffi.C.test_call_pppppii(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6, 7)
954 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6 7")
955
956 ffi.C.test_call_pppppiiiiii(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6, 7, 8, 9, 10, 11)
957 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6 7 8 9 10 11")
958
959 ffi.C.test_call_pppppffffff(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6.5, 7.5, 8.5, 9.5, 10.5, 11.5)
960 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6.5 7.5 8.5 9.5 10.5 11.5")
961
962 ffi.C.test_call_pppppffffffffff(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 11.6, 11.7, 11.8, 11.9)
963 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6.5 7.5 8.5 9.5 10.5 11.5 11.6 11.7 11.8 11.9")
964
965 ffi.C.test_call_pppppiifiii(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6, 7, 8.5, 9, 10, 11)
966 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6 7 8.5 9 10 11")
967
968 ffi.C.test_call_pppppiiifii(ptr(1), ptr(2), ptr(3), ptr(4), ptr(5), 6, 7, 8, 9.5, 10, 11)
969 assert(ffi.C.buf == "0x1 0x2 0x3 0x4 0x5 6 7 8 9.5 10 11")
970
971 local sum = ffi.C.add_dc(ffi.new('complex', 1, 2), ffi.new('complex', 3, 5))
972 assert(ffi.istype('complex', sum))
973
974 sum = ffi.C.add_fc(ffi.new('complex float', 1, 2), ffi.new('complex float', 3, 5))
975 assert(ffi.istype('complex float', sum))
976
977 ffi.cdef [[
978 struct Arrays {
979 int ints[3];
980 unsigned int uints[3];
981 };
982 struct ArrayOfArrays {
983 struct Arrays arrays[3];
984 };
985 ]]
986
987 local struct = ffi.new('struct Arrays')
988 local structOfStructs = ffi.new('struct ArrayOfArrays')
989 for i=0,2 do
990 struct.ints[i] = i
991 struct.uints[i] = i
992 structOfStructs.arrays[0].ints[i] = i
993 end
994 for i=0,2 do
995 assert(struct.ints[i] == i)
996 assert(struct.uints[i] == i)
997 assert(structOfStructs.arrays[0].ints[i] == i)
998 end
999
1000 -- Test ffi.string
1001 local buf = ffi.new('char[5]')
1002 ffi.fill(buf, 4, 97)
1003 buf[4] = 0
1004
1005 assert(ffi.string(buf) == 'aaaa')
1006 assert(ffi.string(buf, 4) == 'aaaa')
1007 assert(ffi.string(buf, 2) == 'aa')
1008 assert(ffi.string(buf, 0) == '')
1009 assert(ffi.string(buf, ffi.new('long long', 2)) == 'aa')
1010 assert(ffi.string(buf, ffi.new('int', 2)) == 'aa')
1011
1012 -- Test io.tmpfile()
1013 ffi.cdef [[
1014 int fprintf ( FILE * stream, const char * format, ... );
1015 ]]
1016 local f = io.tmpfile()
1017 ffi.C.fprintf(f, "test: %s\n", "foo")
1018
1019 f:seek("set", 0)
1020 local str = f:read('*l')
1021 assert(str == 'test: foo', str)
1022 f:close()
1023
1024 -- Test ffi.metatype
1025 -- Ref: https://github.com/openresty/luajit2-test-suite/blob/master/test/ffi/ffi_metatype.lua
1026 local ffi = require('ffi');
1027 ffi.cdef[[
1028 typedef struct { int x; } idx1_t;
1029 typedef struct { int x; } idx2_t;
1030 typedef struct { int x; } idx3_t;
1031 typedef struct { int x,y; } arith_t;
1032 typedef struct { void *p; } gc_t;
1033 ]]
1034
1035 function fails(f, ...)
1036 if pcall(f, ...) ~= false then error("failure expected", 2) end
1037 end
1038
1039 local function ptreq(a, b)
1040 return ffi.cast("void *", a) == ffi.cast("void *", b)
1041 end
1042
1043 do
1044 local nidx = {}
1045 local tp = ffi.metatype("idx1_t", {
1046 __index = { foo = 99, method = function(c, v) return v end },
1047 __newindex = nidx,
1048 })
1049
1050 -- metatable is already set
1051 fails(function() ffi.metatype("idx1_t", {}) end)
1052
1053 local s = tp(1234)
1054 assert(s.foo == 99)
1055 assert(s.x == 1234)
1056 -- bad field in __index metatable
1057 fails(function(s) local x = s.bar; end, s)
1058 assert(s:method(123) == 123)
1059 s.bar = 42
1060 assert(nidx.bar == 42)
1061
1062 local cs = ffi.new("const idx1_t", 9876)
1063 assert(cs.foo == 99)
1064 assert(cs.x == 9876)
1065 -- write to const struct
1066 fails(function(cs) cs.bar = 42 end, cs)
1067
1068 local cp = ffi.new("const idx1_t *", cs)
1069 assert(cp.foo == 99)
1070 assert(cp.x == 9876)
1071 -- write to const struct pointer
1072 fails(function(cp) cp.bar = 42 end, cp)
1073 end
1074
1075 do
1076 local uc, uk, uv
1077 local tp = ffi.metatype("idx2_t", {
1078 __index = function(c, k, x, y)
1079 assert(x == nil and y == nil)
1080 uc, uk = c, k; return 99
1081 end,
1082 __newindex = function(c, k, v) uc, uk, uv = c, k, v end,
1083 })
1084
1085 local s = tp(1234)
1086 assert(s.foo == 99)
1087 assert(ptreq(uc, s) and uk == "foo" and uv == nil); uc,uk,uv=nil,nil,nil
1088 assert(s.x == 1234)
1089 assert(uc == nil and uk == nil and uv == nil); uc,uk,uv=nil,nil,nil
1090
1091 s.bar = 42
1092 assert(ptreq(uc, s) and uk == "bar" and uv == 42); uc,uk,uv=nil,nil,nil
1093 s[10] = 11
1094 assert(ptreq(uc, s) and uk == 10 and uv == 11); uc,uk,uv=nil,nil,nil
1095
1096 local p = ffi.new("idx2_t *", s)
1097 assert(p.foo == 99)
1098 assert(ptreq(uc, p) and uk == "foo" and uv == nil); uc,uk,uv=nil,nil,nil
1099 assert(p.x == 1234)
1100 assert(uc == nil and uk == nil and uv == nil); uc,uk,uv=nil,nil,nil
1101 -- pointer dereference has precedence
1102 assert(ptreq(p[0], p))
1103 assert(uc == nil and uk == nil and uv == nil); uc,uk,uv=nil,nil,nil
1104 -- pointer dereference has precedence
1105 fails(function(p) p[0] = 11 end, p)
1106 end
1107
1108 do
1109 local uc, uk, uv
1110 local ti, tn = {}, {}
1111 local tp = ffi.metatype("idx3_t", {
1112 __index = setmetatable(ti,
1113 { __index = function(c, k) uc, uk = c, k; return 99 end }),
1114 __newindex = setmetatable(tn,
1115 { __newindex = function(c, k, v) uc, uk, uv = c, k, v end }),
1116 })
1117
1118 local s = tp(1234)
1119 assert(s.foo == 99)
1120 assert(uc == ti and uk == "foo" and uv == nil)
1121 uc, uk, uv = nil, nil, nil
1122 assert(s.x == 1234)
1123 assert(uc == nil and uk == nil and uv == nil)
1124
1125 s.bar = 42
1126 assert(uc == tn and uk == "bar" and uv == 42)
1127 uc, uk, uv = nil, nil, nil
1128 s[10] = 11
1129 assert(uc == tn and uk == 10 and uv == 11)
1130 uc, uk, uv = nil, nil, nil
1131 end
1132
1133 do
1134 local tp
1135 tp = ffi.metatype("arith_t", {
1136 __add = function(a, b) return tp(a.x+b.x, a.y+b.y) end,
1137 __sub = function(a, b) return tp(a.x-b.x, a.y-b.y) end,
1138 __mul = function(a, z) return tp(a.x*z, a.y*z) end,
1139 __div = function(z, a) return tp(a.x*z, a.y*z) end,
1140 __concat = setmetatable({}, { __call = function(x) return 99 end }),
1141 __len = function(x) return 2 end,
1142 __call = function(a) return a.x+a.y end,
1143 __tostring = function(a) return "foo" end,
1144 __newindex = function(a, k, v) a.y = v end,
1145 __index = {
1146 diff = function(a) return a.x-a.y end,
1147 },
1148 })
1149
1150 local a = tp(10, 20)
1151 local b = tp(1, 2)
1152 local c = a + b
1153 assert(c.x == 11 and c.y == 22)
1154 assert(c:diff() == -11)
1155 assert(c() == 33)
1156 local d = a - b
1157 assert(d.x == 9 and d.y == 18)
1158 assert(d:diff() == -9)
1159 assert(d() == 27)
1160 local e = a * 3
1161 assert(e.x == 30 and e.y == 60)
1162 --[[
1163 local f = 3LL / a
1164 3LL is part of C syntax, perhaps supported in LuaJit
1165 Adding support in luaffifb will be a huge task
1166 ]]
1167 local f = ffi.new("long long", 3) / a
1168 assert(f.x == 30 and f.y == 60)
1169 assert(1 .. c == 99)
1170 assert(c .. 1 == 99)
1171 assert(c .. d == 99)
1172 assert(tostring(c) == "foo")
1173 assert(tostring(ffi.cast("arith_t *", c)) == "foo")
1174 c.foo = 42
1175 assert(c.y == 42)
1176
1177 local p = ffi.new("arith_t *", a)
1178 local g1 = p + p
1179 assert(g1.x == 20 and g1.y == 40)
1180 local g2 = p[0] + p[0]
1181 assert(g2.x == 20 and g2.y == 40)
1182 assert(p() == 30)
1183
1184 local q = ffi.new("arith_t &", a)
1185 fails(function(p) local y = q[0] + q[0] end, q)
1186 local h = q + q
1187 assert(h.x == 20 and h.y == 40)
1188
1189 local diff = 0
1190 for i=1,100 do diff = a:diff() end
1191 assert(diff == -10)
1192
1193 for i=1,100 do c.foo = i end
1194 assert(c.y == 100)
1195
1196 local z = tp(1, 3)
1197 for i=1,100 do z = z + a end
1198 assert(z.x == 1001 and z.y == 2003)
1199
1200 local x = 0
1201 for i=1,100 do x = x + #a end
1202 assert(x == 200)
1203
1204 local x = 0
1205 for i=1,100 do x = x + p() end
1206 assert(x == 3000)
1207 end
1208
1209 do
1210 local count = 0
1211 local tp = ffi.metatype("gc_t", {
1212 __gc = function(x) count = count + 1 end,
1213 })
1214
1215 local a = tp()
1216 a = nil
1217 collectgarbage()
1218 assert(count == 1)
1219 local b,c = tp(), tp()
1220 b = nil
1221 collectgarbage()
1222 assert(count == 2)
1223 c = nil
1224 collectgarbage()
1225 assert(count == 3)
1226
1227 local z
1228 for i=1,100 do z = tp() end
1229 z = nil
1230 collectgarbage()
1231 assert(count == 103)
1232
1233 local t = {}
1234 for i=1,100 do t[i] = tp() end
1235 for i=1,100 do ffi.gc(t[i], nil) end
1236 t = nil
1237 collectgarbage()
1238 assert(count == 103)
1239 end
1240
1241 --[==[
1242 C++ syntax not supported
1243 do
1244 local tp = ffi.metatype([[
1245 struct {
1246 static const int Z42 = 42;
1247 enum { Z39 = 39 };
1248 int x;
1249 }]], {
1250 __new = function(tp, x)
1251 return ffi.new(tp, x or -1)
1252 end,
1253 __index = { test = function(x) return x+1 end, x = "hello" }
1254 }
1255 )
1256 assert(tp.Z42 == 42)
1257 assert(tp.Z39 == 39)
1258 assert(tp.test(99) == 100)
1259 fails(function() tp.Z42 = 1 end)
1260 fails(function() tp.Z39 = 1 end)
1261 assert(tp.x == "hello") -- Not sure this is a good idea to allow that.
1262 fails(function() tp.x = 1 end)
1263 local o = tp()
1264 o.Z42 = 42;
1265 assert(o.Z42 == 42)
1266 assert(o.Z39 == 39)
1267 assert(o.test(55) == 56)
1268 print(o.Z42);
1269 fails(function() o.Z42 = 1 end)
1270 fails(function() o.Z39 = 1 end)
1271 assert(o.x == -1)
1272 o.x = 5
1273 assert(o.x == 5)
1274 end
1275 ]==]
1276
1277 do
1278 local fb = ffi.new("struct { int x; }", 99);
1279 --[[
1280 __index member supports only functions or tables
1281 local xt = ffi.metatype("struct { }", { __index = fb })
1282 ]]
1283 local xt = ffi.metatype("struct { }", { __index = function (c, n) return fb.x end })
1284 local o = xt()
1285 assert(o.x == 99)
1286 end
1287
1288
1289 print('Test PASSED')