ffi: fix support for generated calls with generic types (for Java FFI)
[nit.git] / src / compiler_ffi.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # FFI support for the compilers
18 module compiler_ffi
19
20 intrude import abstract_compiler
21 intrude import common_ffi
22 import nitni
23
24 redef class MModule
25 private var foreign_callbacks = new ForeignCallbackSet
26 var nitni_ccu: nullable CCompilationUnit = null
27
28 private fun nmodule(v: AbstractCompilerVisitor): nullable AModule
29 do
30 var m2n = v.compiler.modelbuilder.mmodule2nmodule
31 return m2n.get_or_null(self)
32 end
33
34 redef fun finalize_ffi(compiler: AbstractCompiler)
35 do
36 if not uses_ffi then return
37
38 var v = compiler.new_visitor
39 var n = nmodule(v)
40 if n == null then return
41 n.ensure_compile_ffi_wrapper
42 finalize_ffi_wrapper(v.compiler.modelbuilder.compile_dir, v.compiler.mainmodule)
43 for file in ffi_files do v.compiler.extern_bodies.add(file)
44
45 ensure_compile_nitni_base(v)
46
47 nitni_ccu.header_c_types.add("#include \"{name}._ffi.h\"\n")
48
49 nitni_ccu.write_as_nitni(self, v.compiler.modelbuilder.compile_dir)
50
51 for file in nitni_ccu.files do
52 v.compiler.extern_bodies.add(new ExternCFile(file, c_compiler_options))
53 end
54 end
55
56 private fun ensure_compile_nitni_base(v: AbstractCompilerVisitor)
57 do
58 if nitni_ccu != null then return
59
60 nitni_ccu = new CCompilationUnit
61 end
62
63 redef fun collect_linker_libs
64 do
65 var s = c_linker_options
66 if s.is_empty then return null
67 var res = new ArraySet[String]
68 res.add s
69 return res
70 end
71
72 private var compiled_callbacks: Array[NitniCallback] = new Array[NitniCallback]
73
74 # Returns true if callbacks has yet to be generated and register it as being generated
75 private fun check_callback_compilation(cb: NitniCallback): Bool
76 do
77 var compiled = compiled_callbacks.has(cb)
78 if not compiled then compiled_callbacks.add(cb)
79 return not compiled
80 end
81 end
82
83 redef class AExternPropdef
84 private fun compile_ffi_support_to_c(v: AbstractCompilerVisitor)
85 do
86 var mmodule = mpropdef.mclassdef.mmodule
87 var mainmodule = v.compiler.mainmodule
88 var amainmodule = v.compiler.modelbuilder.mmodule2nmodule[mainmodule]
89 var amodule = v.compiler.modelbuilder.mmodule2nmodule[mmodule]
90 var mclass_type = mpropdef.mclassdef.bound_mtype
91
92 # Declare as extern
93 var csignature = mpropdef.mproperty.build_csignature(mclass_type, mmodule, "___impl", long_signature, internal_call_context)
94 v.declare_once("{csignature};")
95
96 # FFI part
97 amodule.ensure_compile_ffi_wrapper
98 compile_ffi_method(mmodule)
99
100 # nitni - Compile missing callbacks
101 mmodule.ensure_compile_nitni_base(v)
102 var ccu = mmodule.nitni_ccu.as(not null)
103
104 for mtype in foreign_callbacks.types do
105 if not mtype.is_cprimitive then
106 mtype.compile_extern_type(v, ccu)
107
108 # has callbacks already been compiled? (this may very well happen with global compilation)
109 if mmodule.check_callback_compilation(mtype) then mtype.compile_extern_helper_functions(v, ccu)
110 end
111 end
112
113 # compile callbacks
114 for cb in foreign_callbacks.callbacks do if mainmodule.check_callback_compilation(cb) then
115 cb.compile_extern_callback(v, ccu)
116 end
117
118 for cb in foreign_callbacks.supers do if mainmodule.check_callback_compilation(cb) then
119 cb.compile_extern_callback(v, ccu)
120 end
121
122 for cb in foreign_callbacks.casts do if mainmodule.check_callback_compilation(cb) then
123 cb.compile_extern_callbacks(v, ccu)
124 end
125
126 # manage nitni callback set
127 mmodule.foreign_callbacks.join(foreign_callbacks)
128 end
129 end
130
131 redef class AExternMethPropdef
132 redef fun compile_to_c(v, mpropdef, arguments)
133 do
134 var mmodule = mpropdef.mclassdef.mmodule
135
136 # if using the old native interface fallback on previous implementation
137 var nextern = self.n_extern
138 if nextern != null then
139 super
140 return
141 end
142
143 mmodule.uses_ffi = true
144
145 var mclass_type = mpropdef.mclassdef.bound_mtype
146
147 # Outgoing code in compiler
148 var externname = mpropdef.mproperty.build_cname(mpropdef.mclassdef.bound_mtype, mmodule, "___impl", long_signature)
149 var recv_var: nullable RuntimeVariable = null
150 var return_mtype = mpropdef.msignature.return_mtype
151 if return_mtype != null then
152 return_mtype = return_mtype.anchor_to(mmodule, mclass_type)
153 recv_var = v.new_var(return_mtype)
154 end
155
156 v.adapt_signature(mpropdef, arguments)
157
158 var arguments_for_c = new Array[String]
159 for a in [0..arguments.length[ do
160 var arg = arguments[a]
161 var param_mtype: MType
162 if a == 0 then
163 param_mtype = mpropdef.mclassdef.mclass.mclass_type
164 else param_mtype = mpropdef.msignature.mparameters[a-1].mtype
165
166 param_mtype = param_mtype.anchor_to(mmodule, mclass_type)
167
168 if param_mtype.is_cprimitive then
169 arguments_for_c.add(arg.name)
170 else
171 v.add("struct nitni_instance* var_for_c_{a};")
172 v.add("var_for_c_{a} = malloc(sizeof(struct nitni_instance));")
173 v.add("var_for_c_{a}->value = {arg.name};")
174 arguments_for_c.add("var_for_c_{a}")
175 end
176 end
177
178 if recv_var == null then
179 v.add("{externname}({arguments_for_c.join(", ")});")
180 else
181 assert return_mtype != null
182 if return_mtype.is_cprimitive then
183 v.add("{recv_var} = {externname}({arguments_for_c.join(", ")});")
184 else
185 v.add("struct nitni_instance* ret_var;")
186 v.add("ret_var = {externname}({arguments_for_c.join(", ")});")
187 v.add("{recv_var} = ret_var->value;")
188 end
189 v.ret(recv_var)
190 end
191
192 compile_ffi_support_to_c(v)
193 end
194 end
195
196 redef class AExternInitPropdef
197 redef fun compile_to_c(v, mpropdef, arguments)
198 do
199 var mmodule = mpropdef.mclassdef.mmodule
200
201 # if using the old native interface fallback on previous implementation
202 var nextern = self.n_extern
203 if nextern != null then
204 super
205 return
206 end
207
208 mmodule.uses_ffi = true
209
210 var mclass_type = mpropdef.mclassdef.bound_mtype
211
212 var externname = mpropdef.mproperty.build_cname(mpropdef.mclassdef.bound_mtype, mmodule, "___impl", long_signature)
213 var return_mtype = arguments.first.mtype
214 var recv_var = v.new_var(return_mtype)
215
216 v.adapt_signature(mpropdef, arguments)
217
218 arguments.shift
219
220 var arguments_for_c = new Array[String]
221 for a in [0..arguments.length[ do
222 var arg = arguments[a]
223 var param_mtype: MType
224 param_mtype = mpropdef.msignature.mparameters[a].mtype
225 param_mtype = param_mtype.anchor_to(mmodule, mclass_type)
226
227 if param_mtype.is_cprimitive then
228 arguments_for_c.add(arg.name)
229 else
230 v.add("struct nitni_instance* var_for_c_{a};")
231 v.add("var_for_c_{a} = malloc(sizeof(struct nitni_instance));")
232 v.add("var_for_c_{a}->value = {arg.name};")
233 arguments_for_c.add("var_for_c_{a}")
234 end
235 end
236
237 if return_mtype.is_cprimitive then
238 v.add("{recv_var} = {externname}({arguments_for_c.join(", ")});")
239 else
240 v.add("struct nitni_instance* ret_var;")
241 v.add("ret_var = {externname}({arguments_for_c.join(", ")});")
242 v.add("{recv_var} = ret_var->value;")
243 end
244 v.ret(recv_var)
245
246 compile_ffi_support_to_c(v)
247 end
248 end
249
250 redef class CCompilationUnit
251 fun write_as_nitni(mmodule: MModule, compdir: String)
252 do
253 var base_name = "{mmodule.name}._nitni"
254
255 var h_file = "{base_name}.h"
256 write_header_to_file( mmodule, "{compdir}/{h_file}", new Array[String],
257 "{mmodule.cname.to_s.to_upper}_NITG_NITNI_H")
258
259 var c_file = "{base_name}.c"
260 write_body_to_file( mmodule, "{compdir}/{c_file}", ["\"{h_file}\""] )
261
262 files.add( "{compdir}/{c_file}" )
263 end
264 end
265
266 redef class AbstractCompilerVisitor
267 # Create a `RuntimeVariable` for this C variable originating from C user code
268 private fun var_from_c(name: String, mtype: MType): RuntimeVariable
269 do
270 if mtype.is_cprimitive then
271 return new RuntimeVariable(name, mtype, mtype)
272 else
273 return new RuntimeVariable("{name}->value", mtype, mtype)
274 end
275 end
276
277 # Return a `RuntimeVarible` to C user code
278 private fun ret_to_c(src: RuntimeVariable, mtype: MType)
279 do
280 if mtype.is_cprimitive then
281 add("return {src};")
282 else
283 add("struct nitni_instance* ret_for_c;")
284 add("ret_for_c = malloc(sizeof(struct nitni_instance));")
285 add("ret_for_c->value = {src};")
286 add("return ret_for_c;")
287 end
288 end
289 end
290
291 redef class MType
292 private fun compile_extern_type(v: AbstractCompilerVisitor, ccu: CCompilationUnit)
293 do
294 assert not is_cprimitive
295
296 # define friendly type
297 ccu.header_c_types.add("#ifndef NIT_TYPE_{cname}\n")
298 ccu.header_c_types.add("#define NIT_TYPE_{cname} 1\n")
299 ccu.header_c_types.add("typedef struct nitni_instance *{cname};\n")
300 ccu.header_c_types.add("#endif\n")
301 end
302
303 private fun compile_extern_helper_functions(v: AbstractCompilerVisitor, ccu: CCompilationUnit)
304 do
305 # actually, we do not need to do anything when using the bohem garbage collector
306
307 # incr_ref
308 var nitni_visitor = v.compiler.new_visitor
309 ccu.header_decl.add("#define {mangled_cname}_incr_ref(from) while(0)\{\}\n")
310
311 # incr_ref
312 nitni_visitor = v.compiler.new_visitor
313 ccu.header_decl.add("#define {mangled_cname}_decr_ref(from) while(0)\{\}\n")
314 end
315 end
316
317 redef class MNullableType
318 redef fun compile_extern_helper_functions(v, ccu)
319 do
320 super
321
322 var base_cname = "null_{mtype.mangled_cname}"
323 var full_cname = "NIT_NULL___{base_cname}"
324
325 # In nitni files, declare internal function as extern
326 var full_friendly_csignature = "{cname_blind} {full_cname}()"
327 ccu.header_decl.add("extern {full_friendly_csignature};\n")
328
329 # In nitni files, #define friendly as extern
330 ccu.header_decl.add("#define {base_cname} {full_cname}\n")
331
332 # FIXME: This is ugly an broke the separate compilation principle
333 # The real function MUST be compiled only once, #define pragma only protect the compiler, not the loader
334 # However, I am not sure of the right approach here (eg. week refs are ugly)
335 if is_already_compiled then return
336 is_already_compiled = true
337
338 # Internally, implement internal function
339 var nitni_visitor = v.compiler.new_visitor
340 nitni_visitor.frame = v.frame
341 var full_internal_csignature = "{cname_blind} {full_cname}()"
342 nitni_visitor.add("{full_internal_csignature} \{")
343 nitni_visitor.add("struct nitni_instance* ret_for_c;")
344 nitni_visitor.add("ret_for_c = malloc(sizeof(struct nitni_instance));")
345 nitni_visitor.add("ret_for_c->value = NULL;")
346 nitni_visitor.add("return ret_for_c;")
347 nitni_visitor.add("\}")
348 end
349
350 private var is_already_compiled = false # FIXME to remove, show above
351 end
352
353 redef class MExplicitCall
354 private fun compile_extern_callback(v: AbstractCompilerVisitor, ccu: CCompilationUnit)
355 do
356 var mproperty = mproperty
357 assert mproperty isa MMethod
358
359 # In nitni files, declare internal function as extern
360 var full_friendly_csignature = mproperty.build_csignature(recv_mtype, v.compiler.mainmodule, null, long_signature, internal_call_context)
361 ccu.header_decl.add("extern {full_friendly_csignature};\n")
362
363 # Internally, implement internal function
364 var nitni_visitor = v.compiler.new_visitor
365 nitni_visitor.frame = v.frame
366 var msignature = mproperty.lookup_first_definition(v.compiler.mainmodule, recv_mtype).msignature
367 var csignature_blind = mproperty.build_csignature(recv_mtype, v.compiler.mainmodule, null, long_signature, internal_call_context)
368
369 nitni_visitor.add_decl("/* nitni callback for {mproperty.full_name} */")
370 nitni_visitor.add_decl("{csignature_blind} \{")
371
372 var vars = new Array[RuntimeVariable]
373 var mtype: MType = recv_mtype
374 var recv_var = null
375 if mproperty.is_init then
376 if recv_mtype.mclass.kind == extern_kind then
377 recv_var = nitni_visitor.new_var(mtype)
378 else
379 var recv_mtype = recv_mtype
380 recv_var = nitni_visitor.init_instance(recv_mtype)
381 nitni_visitor.add("{mtype.ctype} recv /* var self: {mtype} */;")
382 nitni_visitor.add("recv = {recv_var};")
383 end
384 else
385 mtype = mtype.anchor_to(v.compiler.mainmodule, recv_mtype)
386 recv_var = nitni_visitor.var_from_c("recv", mtype)
387 end
388
389 vars.add(recv_var)
390
391 for p in msignature.mparameters do
392 var arg_mtype = p.mtype.anchor_to(v.compiler.mainmodule, recv_mtype)
393 var arg = nitni_visitor.var_from_c(p.name, arg_mtype)
394 vars.add(arg)
395 end
396
397 var ret_var = nitni_visitor.send(mproperty, vars)
398
399 var return_mtype = msignature.return_mtype
400 if mproperty.is_init then
401 if recv_mtype.mclass.kind != extern_kind then ret_var = recv_var
402 return_mtype = recv_mtype
403 end
404 if return_mtype != null then
405 assert ret_var != null
406 return_mtype = return_mtype.anchor_to(v.compiler.mainmodule, recv_mtype)
407 ret_var = nitni_visitor.autobox(ret_var, return_mtype)
408 nitni_visitor.ret_to_c(ret_var, return_mtype)
409 end
410 nitni_visitor.add("\}")
411 end
412 end
413
414 redef class MExplicitSuper
415 private fun compile_extern_callback(v: AbstractCompilerVisitor, ccu: CCompilationUnit)
416 do
417 var mproperty = from.mproperty
418 assert mproperty isa MMethod
419 var mclass_type = from.mclassdef.mclass.mclass_type
420 var mmodule = from.mclassdef.mmodule
421
422 # In nitni files, declare internal function as extern
423 var internal_csignature = mproperty.build_csignature(mclass_type, v.compiler.mainmodule, "___super", long_signature, internal_call_context)
424 ccu.header_decl.add("extern {internal_csignature};\n")
425
426 # In nitni files, #define friendly as extern
427 var friendly_cname = mproperty.build_cname(mclass_type, v.compiler.mainmodule, "___super", short_signature)
428 var internal_cname = mproperty.build_cname(mclass_type, v.compiler.mainmodule, "___super", long_signature)
429 ccu.header_decl.add("#define {friendly_cname} {internal_cname}\n")
430
431 # Internally, implement internal function
432 var nitni_visitor = v.compiler.new_visitor
433 nitni_visitor.frame = v.frame
434 var msignature = mproperty.lookup_first_definition(v.compiler.mainmodule, mclass_type).msignature
435
436 var csignature_blind = mproperty.build_csignature(mclass_type, v.compiler.mainmodule, "___super", long_signature, internal_call_context)
437
438 nitni_visitor.add_decl("/* nitni callback to super for {mproperty.full_name} */")
439 nitni_visitor.add_decl("{csignature_blind} \{")
440
441 var vars = new Array[RuntimeVariable]
442
443 var recv_var = nitni_visitor.var_from_c("recv", mclass_type)
444 vars.add(recv_var)
445
446 for p in msignature.mparameters do
447 var arg_mtype = v.anchor(p.mtype)
448 var arg = nitni_visitor.var_from_c(p.name, arg_mtype)
449 vars.add(arg)
450 end
451
452 var ret_var = nitni_visitor.supercall(from.as(MMethodDef), mclass_type, vars)
453
454 var return_mtype = msignature.return_mtype
455 if return_mtype != null then
456 assert ret_var != null
457 return_mtype = v.anchor(return_mtype)
458 nitni_visitor.ret_to_c(ret_var, return_mtype)
459 end
460 nitni_visitor.add("\}")
461 end
462 end
463
464 redef class MExplicitCast
465 private fun compile_extern_callbacks(v: AbstractCompilerVisitor, ccu: CCompilationUnit)
466 do
467 var from = from
468 var to = to
469
470 #
471 ## check type
472 #
473
474 # In nitni files, declare internal function as extern
475 var full_friendly_csignature = "int {v.compiler.mainmodule.name }___{from.mangled_cname}_is_a_{to.mangled_cname}({from.cname_blind})"
476 ccu.header_decl.add("extern {full_friendly_csignature};\n")
477
478 # In nitni files, #define friendly as extern
479 ccu.header_decl.add("#define {check_cname} {v.compiler.mainmodule.name}___{check_cname}\n")
480
481 # Internally, implement internal function
482 var nitni_visitor = v.compiler.new_visitor
483 nitni_visitor.frame = v.frame
484
485 var full_internal_csignature = "int {v.compiler.mainmodule.name }___{from.mangled_cname}_is_a_{to.mangled_cname}({from.cname_blind} from)"
486 nitni_visitor.add_decl("/* nitni check for {from} to {to} */")
487 nitni_visitor.add_decl("{full_internal_csignature} \{")
488
489 var from_var = new RuntimeVariable("from->value", from, from)
490 var recv_var = nitni_visitor.type_test(from_var, to, "FFI isa")
491 nitni_visitor.add("return {recv_var};")
492
493 nitni_visitor.add("\}")
494
495 # special checks
496 if from == to.as_nullable then
497 # format A_is_null
498 ccu.header_decl.add("#define {from.mangled_cname}_is_null !{from.mangled_cname}_is_a_{to.mangled_cname}\n")
499 end
500
501 #
502 ## cast
503 #
504
505 # In nitni files, declare internal function as extern
506 full_friendly_csignature = "{to.cname_blind} {v.compiler.mainmodule.name }___{from.mangled_cname}_as_{to.mangled_cname}({from.cname_blind})"
507 ccu.header_decl.add("extern {full_friendly_csignature};\n")
508
509 # In nitni files, #define friendly as extern
510 ccu.header_decl.add("#define {cast_cname} {v.compiler.mainmodule.name}___{cast_cname}\n")
511
512 # Internally, implement internal function
513 nitni_visitor = v.compiler.new_visitor
514 nitni_visitor.frame = v.frame
515
516 full_internal_csignature = "{to.cname_blind} {v.compiler.mainmodule.name }___{from.mangled_cname}_as_{to.mangled_cname}({from.cname_blind} from)"
517 nitni_visitor.add_decl("/* nitni cast for {from} to {to} */")
518 nitni_visitor.add_decl("{full_internal_csignature} \{")
519
520 from_var = nitni_visitor.var_from_c("from", from)
521
522 ## test type
523 var check = nitni_visitor.type_test(from_var, to, "FFI cast")
524 nitni_visitor.add("if (!{check}) \{")
525 nitni_visitor.add_abort("FFI cast failed")
526 nitni_visitor.add("\}")
527
528 ## internal cast
529 recv_var = nitni_visitor.autobox(from_var, to)
530
531 nitni_visitor.ret_to_c(recv_var, to)
532
533 nitni_visitor.add("\}")
534
535 # special casts
536 if from.as_nullable == to then
537 # format A_as_nullable
538 ccu.header_decl.add("#define {from.mangled_cname}_as_nullable {from.mangled_cname}_as_{to.mangled_cname}\n")
539 end
540
541 if from == to.as_nullable then
542 # format A_as_nullable
543 ccu.header_decl.add("#define {to.mangled_cname}_as_not_nullable {from.mangled_cname}_as_{to.mangled_cname}\n")
544 end
545 end
546 end