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