Debian Codegraph @

texk/web2c/luatexdir/luaffi/test.lua.orig

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