1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # FFI support for the compilers
20 intrude import abstract_compiler
25 private var foreign_callbacks
= new ForeignCallbackSet
26 var nitni_ccu
: nullable CCompilationUnit = null
28 private fun nmodule
(v
: AbstractCompilerVisitor): nullable AModule
30 var m2n
= v
.compiler
.modelbuilder
.mmodule2nmodule
31 return m2n
.get_or_null
(self)
34 redef fun finalize_ffi
(compiler
: AbstractCompiler)
36 if not uses_ffi
then return
38 var v
= compiler
.new_visitor
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
)
45 ensure_compile_nitni_base
(v
)
47 nitni_ccu
.header_c_types
.add
("#include \"{name}._ffi
.h\
"\n")
48 nitni_ccu
.header_c_types
.add
"""
49 extern void nitni_global_ref_incr(void*);
50 extern void nitni_global_ref_decr(void*);
53 nitni_ccu
.write_as_nitni
(self, v
.compiler
.modelbuilder
.compile_dir
)
55 for file
in nitni_ccu
.files
do
56 v
.compiler
.extern_bodies
.add
(new ExternCFile(file
, c_compiler_options
))
59 # reset FFI things so the next compilation job, if any, starts with a clean context
60 # FIXME clean and rationalize this
62 compiled_ffi_methods
.clear
65 compiled_callbacks
.clear
66 #Do not reset `foreign_callbacks` and `ffi_callbacks` because they are computed in previous phases
69 private fun ensure_compile_nitni_base
(v
: AbstractCompilerVisitor)
71 if nitni_ccu
!= null then return
73 nitni_ccu
= new CCompilationUnit
76 redef fun collect_linker_libs
78 var s
= c_linker_options
79 if s
.is_empty
then return null
80 var res
= new ArraySet[String]
85 private var compiled_callbacks
= new Array[NitniCallback]
87 # Returns true if callbacks has yet to be generated and register it as being generated
88 private fun check_callback_compilation
(cb
: NitniCallback): Bool
90 var compiled
= compiled_callbacks
.has
(cb
)
91 if not compiled
then compiled_callbacks
.add
(cb
)
96 redef class AMethPropdef
97 private fun compile_ffi_support_to_c
(v
: AbstractCompilerVisitor)
99 var mmodule
= mpropdef
.mclassdef
.mmodule
100 var mainmodule
= v
.compiler
.mainmodule
101 var amodule
= v
.compiler
.modelbuilder
.mmodule2nmodule
[mmodule
]
102 var mclass_type
= mpropdef
.mclassdef
.bound_mtype
105 var csignature
= mpropdef
.mproperty
.build_csignature
(mclass_type
, mmodule
, "___impl", long_signature
, internal_call_context
)
106 v
.declare_once
("{csignature};")
109 amodule
.ensure_compile_ffi_wrapper
110 compile_ffi_method
(mmodule
)
112 # nitni - Compile missing callbacks
113 mmodule
.ensure_compile_nitni_base
(v
)
114 var ccu
= mmodule
.nitni_ccu
.as(not null)
116 for mtype
in foreign_callbacks
.types
do
117 if not mtype
.is_cprimitive
then
118 mtype
.compile_extern_type
(v
, ccu
)
120 # has callbacks already been compiled? (this may very well happen with global compilation)
121 if mmodule
.check_callback_compilation
(mtype
) then mtype
.compile_extern_helper_functions
(v
, ccu
)
126 for cb
in foreign_callbacks
.callbacks
do if mainmodule
.check_callback_compilation
(cb
) then
127 cb
.compile_extern_callback
(v
, ccu
)
130 for cb
in foreign_callbacks
.supers
do if mainmodule
.check_callback_compilation
(cb
) then
131 cb
.compile_extern_callback
(v
, ccu
)
134 for cb
in foreign_callbacks
.casts
do if mainmodule
.check_callback_compilation
(cb
) then
135 cb
.compile_extern_callbacks
(v
, ccu
)
138 # manage nitni callback set
139 mmodule
.foreign_callbacks
.join
(foreign_callbacks
)
142 redef fun compile_externmeth_to_c
(v
, mpropdef
, arguments
)
144 # if using the old native interface fallback on previous implementation
145 if n_extern_code_block
== null then return super
147 var mmodule
= mpropdef
.mclassdef
.mmodule
148 mmodule
.uses_ffi
= true
150 var mclass_type
= mpropdef
.mclassdef
.bound_mtype
152 # Outgoing code in compiler
153 var externname
= mpropdef
.mproperty
.build_cname
(mpropdef
.mclassdef
.bound_mtype
, mmodule
, "___impl", long_signature
)
154 var recv_var
: nullable RuntimeVariable = null
155 var return_mtype
= mpropdef
.msignature
.return_mtype
156 if return_mtype
!= null then
157 return_mtype
= return_mtype
.anchor_to
(mmodule
, mclass_type
)
158 recv_var
= v
.new_var
(return_mtype
)
161 v
.adapt_signature
(mpropdef
, arguments
)
162 v
.unbox_signature_extern
(mpropdef
, arguments
)
164 var arguments_for_c
= new Array[String]
165 for a
in [0..arguments
.length
[ do
166 var arg
= arguments
[a
]
167 var param_mtype
: MType
169 param_mtype
= mpropdef
.mclassdef
.mclass
.mclass_type
170 else param_mtype
= mpropdef
.msignature
.mparameters
[a-1
].mtype
172 param_mtype
= param_mtype
.anchor_to
(mmodule
, mclass_type
)
174 if param_mtype
.is_cprimitive
then
175 arguments_for_c
.add
(arg
.name
)
177 v
.add
("struct nitni_instance* var_for_c_{a};")
178 v
.add
("var_for_c_{a} = nit_alloc(sizeof(struct nitni_instance));")
179 v
.add
("var_for_c_{a}->value = {arg.name};")
180 arguments_for_c
.add
("var_for_c_{a}")
184 if recv_var
== null then
185 v
.add
("{externname}({arguments_for_c.join(", ")});")
187 assert return_mtype
!= null
188 if return_mtype
.is_cprimitive
then
189 v
.add
("{recv_var} = {externname}({arguments_for_c.join(", ")});")
191 v
.add
("struct nitni_instance* ret_var;")
192 v
.add
("ret_var = {externname}({arguments_for_c.join(", ")});")
193 v
.add
("{recv_var} = ret_var->value;")
195 recv_var
= v
.box_extern
(recv_var
, return_mtype
)
199 compile_ffi_support_to_c
(v
)
203 redef fun compile_externinit_to_c
(v
, mpropdef
, arguments
)
205 # if using the old native interface fallback on previous implementation
206 if n_extern_code_block
== null then return super
208 var mmodule
= mpropdef
.mclassdef
.mmodule
209 mmodule
.uses_ffi
= true
211 var mclass_type
= mpropdef
.mclassdef
.bound_mtype
213 var externname
= mpropdef
.mproperty
.build_cname
(mpropdef
.mclassdef
.bound_mtype
, mmodule
, "___impl", long_signature
)
214 var return_mtype
= arguments
.first
.mtype
215 var recv_var
= v
.new_var
(return_mtype
)
217 v
.adapt_signature
(mpropdef
, arguments
)
218 v
.unbox_signature_extern
(mpropdef
, arguments
)
222 var arguments_for_c
= new Array[String]
223 for a
in [0..arguments
.length
[ do
224 var arg
= arguments
[a
]
225 var param_mtype
: MType
226 param_mtype
= mpropdef
.msignature
.mparameters
[a
].mtype
227 param_mtype
= param_mtype
.anchor_to
(mmodule
, mclass_type
)
229 if param_mtype
.is_cprimitive
then
230 arguments_for_c
.add
(arg
.name
)
232 v
.add
("struct nitni_instance* var_for_c_{a};")
233 v
.add
("var_for_c_{a} = nit_alloc(sizeof(struct nitni_instance));")
234 v
.add
("var_for_c_{a}->value = {arg.name};")
235 arguments_for_c
.add
("var_for_c_{a}")
239 if return_mtype
.is_cprimitive
then
240 v
.add
("{recv_var} = {externname}({arguments_for_c.join(", ")});")
242 v
.add
("struct nitni_instance* ret_var;")
243 v
.add
("ret_var = {externname}({arguments_for_c.join(", ")});")
244 v
.add
("{recv_var} = ret_var->value;")
246 recv_var
= v
.box_extern
(recv_var
, return_mtype
)
249 compile_ffi_support_to_c
(v
)
254 redef class CCompilationUnit
255 fun write_as_nitni
(mmodule
: MModule, compdir
: String)
257 var base_name
= "{mmodule.name}._nitni"
259 var h_file
= "{base_name}.h"
260 write_header_to_file
( mmodule
, "{compdir}/{h_file}", new Array[String],
261 "{mmodule.cname.to_s.to_upper}_NITG_NITNI_H")
263 var c_file
= "{base_name}.c"
264 write_body_to_file
( mmodule
, "{compdir}/{c_file}", ["\"{h_file}\
""] )
266 files
.add
( "{compdir}/{c_file}" )
270 redef class AbstractCompiler
271 # Cache to avoid multiple compilation of NULL values
272 # see FIXME in `MNullableType#compile_extern_helper_functions`
273 private var compiled_null_types
= new Array[MNullableType]
276 redef class AbstractCompilerVisitor
277 # Create a `RuntimeVariable` for this C variable originating from C user code
278 private fun var_from_c
(name
: String, mtype
: MType): RuntimeVariable
280 if mtype
.is_cprimitive
then
281 return new RuntimeVariable(name
, mtype
, mtype
)
283 return new RuntimeVariable("{name}->value", mtype
, mtype
)
287 # Return a `RuntimeVarible` to C user code
288 private fun ret_to_c
(src
: RuntimeVariable, mtype
: MType)
290 if mtype
.is_cprimitive
then
293 add
("struct nitni_instance* ret_for_c;")
294 add
("ret_for_c = nit_alloc(sizeof(struct nitni_instance));")
295 add
("ret_for_c->value = {src};")
296 add
("return ret_for_c;")
302 private fun compile_extern_type
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
304 assert not is_cprimitive
306 # define friendly type
307 ccu
.header_c_types
.add
("#ifndef NIT_TYPE_{cname}\n")
308 ccu
.header_c_types
.add
("#define NIT_TYPE_{cname} 1\n")
309 ccu
.header_c_types
.add
("typedef struct nitni_instance *{cname};\n")
310 ccu
.header_c_types
.add
("#endif\n")
313 private fun compile_extern_helper_functions
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
315 # actually, we do not need to do anything when using the bohem garbage collector
316 var call_context
= from_c_call_context
319 ccu
.header_decl
.add
"#ifndef {mangled_cname}_incr_ref\n"
320 ccu
.header_decl
.add
" #define {mangled_cname}_incr_ref(from) nitni_global_ref_incr(({call_context.name_mtype(self)})(from))\n"
321 ccu
.header_decl
.add
"#endif\n"
324 ccu
.header_decl
.add
"#ifndef {mangled_cname}_decr_ref\n"
325 ccu
.header_decl
.add
" #define {mangled_cname}_decr_ref(from) nitni_global_ref_decr(({call_context.name_mtype(self)})(from))\n"
326 ccu
.header_decl
.add
"#endif\n"
330 redef class MNullableType
331 redef fun compile_extern_helper_functions
(v
, ccu
)
335 var base_cname
= "null_{mtype.mangled_cname}"
336 var full_cname
= "NIT_NULL___{base_cname}"
338 # In nitni files, declare internal function as extern
339 var full_friendly_csignature
= "{cname_blind} {full_cname}()"
340 ccu
.header_decl
.add
("extern {full_friendly_csignature};\n")
342 # In nitni files, #define friendly as extern
343 ccu
.header_decl
.add
("#define {base_cname} {full_cname}\n")
345 # FIXME: This is ugly an broke the separate compilation principle
346 # The real function MUST be compiled only once, #define pragma only protect the compiler, not the loader
347 # However, I am not sure of the right approach here (eg. week refs are ugly)
348 if v
.compiler
.compiled_null_types
.has
(self) then return
349 v
.compiler
.compiled_null_types
.add
self
351 # Internally, implement internal function
352 var nitni_visitor
= v
.compiler
.new_visitor
353 nitni_visitor
.frame
= v
.frame
354 var full_internal_csignature
= "{cname_blind} {full_cname}()"
355 nitni_visitor
.add
("{full_internal_csignature} \{")
356 nitni_visitor
.add
("struct nitni_instance* ret_for_c;")
357 nitni_visitor
.add
("ret_for_c = nit_alloc(sizeof(struct nitni_instance));")
358 nitni_visitor
.add
("ret_for_c->value = NULL;")
359 nitni_visitor
.add
("return ret_for_c;")
360 nitni_visitor
.add
("\}")
364 redef class MExplicitCall
365 private fun compile_extern_callback
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
367 var mproperty
= mproperty
368 assert mproperty
isa MMethod
370 # In nitni files, declare internal function as extern
371 var full_friendly_csignature
= mproperty
.build_csignature
(recv_mtype
, v
.compiler
.mainmodule
, null, long_signature
, internal_call_context
)
372 ccu
.header_decl
.add
("extern {full_friendly_csignature};\n")
374 # Internally, implement internal function
375 var nitni_visitor
= v
.compiler
.new_visitor
376 nitni_visitor
.frame
= v
.frame
377 var msignature
= mproperty
.lookup_first_definition
(v
.compiler
.mainmodule
, recv_mtype
).msignature
378 var csignature_blind
= mproperty
.build_csignature
(recv_mtype
, v
.compiler
.mainmodule
, null, long_signature
, internal_call_context
)
380 nitni_visitor
.add_decl
("/* nitni callback for {mproperty.full_name} */")
381 nitni_visitor
.add_decl
("{csignature_blind} \{")
383 var vars
= new Array[RuntimeVariable]
384 var mtype
: MType = recv_mtype
386 if mproperty
.is_init
then
387 var recv_mtype
= recv_mtype
388 recv_var
= nitni_visitor
.init_instance
(recv_mtype
)
389 nitni_visitor
.add
("{mtype.ctype} recv /* var self: {mtype} */;")
390 nitni_visitor
.add
("recv = {recv_var};")
392 mtype
= mtype
.anchor_to
(v
.compiler
.mainmodule
, recv_mtype
)
393 recv_var
= nitni_visitor
.var_from_c
("recv", mtype
)
394 recv_var
= nitni_visitor
.box_extern
(recv_var
, mtype
)
399 for p
in msignature
.mparameters
do
400 var arg_mtype
= p
.mtype
.anchor_to
(v
.compiler
.mainmodule
, recv_mtype
)
401 var arg
= nitni_visitor
.var_from_c
(p
.name
, arg_mtype
)
402 arg
= nitni_visitor
.box_extern
(arg
, arg_mtype
)
406 var ret_var
= nitni_visitor
.send
(mproperty
, vars
)
408 var return_mtype
= msignature
.return_mtype
409 if mproperty
.is_init
then
410 if recv_mtype
.mclass
.kind
!= extern_kind
then ret_var
= recv_var
411 return_mtype
= recv_mtype
413 if return_mtype
!= null then
414 assert ret_var
!= null
415 return_mtype
= return_mtype
.anchor_to
(v
.compiler
.mainmodule
, recv_mtype
)
416 ret_var
= nitni_visitor
.autobox
(ret_var
, return_mtype
)
417 ret_var
= nitni_visitor
.unbox_extern
(ret_var
, return_mtype
)
418 nitni_visitor
.ret_to_c
(ret_var
, return_mtype
)
420 nitni_visitor
.add
("\}")
424 redef class MExplicitSuper
425 private fun compile_extern_callback
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
427 var mproperty
= from
.mproperty
428 assert mproperty
isa MMethod
429 var mclass_type
= from
.mclassdef
.mclass
.mclass_type
431 # In nitni files, declare internal function as extern
432 var internal_csignature
= mproperty
.build_csignature
(mclass_type
, v
.compiler
.mainmodule
, "___super", long_signature
, internal_call_context
)
433 ccu
.header_decl
.add
("extern {internal_csignature};\n")
435 # In nitni files, #define friendly as extern
436 var friendly_cname
= mproperty
.build_cname
(mclass_type
, v
.compiler
.mainmodule
, "___super", short_signature
)
437 var internal_cname
= mproperty
.build_cname
(mclass_type
, v
.compiler
.mainmodule
, "___super", long_signature
)
438 ccu
.header_decl
.add
("#define {friendly_cname} {internal_cname}\n")
440 # Internally, implement internal function
441 var nitni_visitor
= v
.compiler
.new_visitor
442 nitni_visitor
.frame
= v
.frame
443 var msignature
= mproperty
.lookup_first_definition
(v
.compiler
.mainmodule
, mclass_type
).msignature
445 var csignature_blind
= mproperty
.build_csignature
(mclass_type
, v
.compiler
.mainmodule
, "___super", long_signature
, internal_call_context
)
447 nitni_visitor
.add_decl
("/* nitni callback to super for {mproperty.full_name} */")
448 nitni_visitor
.add_decl
("{csignature_blind} \{")
450 var vars
= new Array[RuntimeVariable]
452 var recv_var
= nitni_visitor
.var_from_c
("recv", mclass_type
)
453 recv_var
= nitni_visitor
.box_extern
(recv_var
, mclass_type
)
456 for p
in msignature
.mparameters
do
457 var arg_mtype
= v
.anchor
(p
.mtype
)
458 var arg
= nitni_visitor
.var_from_c
(p
.name
, arg_mtype
)
459 arg
= nitni_visitor
.box_extern
(arg
, arg_mtype
)
463 var ret_var
= nitni_visitor
.supercall
(from
.as(MMethodDef), mclass_type
, vars
)
465 var return_mtype
= msignature
.return_mtype
466 if return_mtype
!= null then
467 assert ret_var
!= null
468 return_mtype
= v
.anchor
(return_mtype
)
469 ret_var
= nitni_visitor
.autobox
(ret_var
, return_mtype
)
470 ret_var
= nitni_visitor
.unbox_extern
(ret_var
, return_mtype
)
471 nitni_visitor
.ret_to_c
(ret_var
, return_mtype
)
473 nitni_visitor
.add
("\}")
477 redef class MExplicitCast
478 private fun compile_extern_callbacks
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
487 # In nitni files, declare internal function as extern
488 var full_friendly_csignature
= "int {v.compiler.mainmodule.name }___{from.mangled_cname}_is_a_{to.mangled_cname}({from.cname_blind})"
489 ccu
.header_decl
.add
("extern {full_friendly_csignature};\n")
491 # In nitni files, #define friendly as extern
492 ccu
.header_decl
.add
("#define {check_cname} {v.compiler.mainmodule.name}___{check_cname}\n")
494 # Internally, implement internal function
495 var nitni_visitor
= v
.compiler
.new_visitor
496 nitni_visitor
.frame
= v
.frame
498 var full_internal_csignature
= "int {v.compiler.mainmodule.name }___{from.mangled_cname}_is_a_{to.mangled_cname}({internal_call_context.name_mtype(from)} from)"
500 nitni_visitor
.add_decl
("/* nitni check for {from} to {to} */")
501 nitni_visitor
.add_decl
("{full_internal_csignature} \{")
503 #var from_var = new RuntimeVariable("from->value", from, from)
504 var from_var
= nitni_visitor
.var_from_c
("from", from
)
505 from_var
= nitni_visitor
.box_extern
(from_var
, from
)
506 var recv_var
= nitni_visitor
.type_test
(from_var
, to
, "FFI isa")
507 nitni_visitor
.add
("return {recv_var};")
509 nitni_visitor
.add
("\}")
512 if from
== to
.as_nullable
then
514 ccu
.header_decl
.add
("#define {from.mangled_cname}_is_null !{from.mangled_cname}_is_a_{to.mangled_cname}\n")
521 # In nitni files, declare internal function as extern
522 full_friendly_csignature
= "{to.cname_blind} {v.compiler.mainmodule.name }___{from.mangled_cname}_as_{to.mangled_cname}({from.cname_blind})"
523 ccu
.header_decl
.add
("extern {full_friendly_csignature};\n")
525 # In nitni files, #define friendly as extern
526 ccu
.header_decl
.add
("#define {cast_cname} {v.compiler.mainmodule.name}___{cast_cname}\n")
528 # Internally, implement internal function
529 nitni_visitor
= v
.compiler
.new_visitor
530 nitni_visitor
.frame
= v
.frame
532 full_internal_csignature
= "{to.cname_blind} {v.compiler.mainmodule.name }___{from.mangled_cname}_as_{to.mangled_cname}({internal_call_context.name_mtype(from)} from)"
533 nitni_visitor
.add_decl
("/* nitni cast for {from} to {to} */")
534 nitni_visitor
.add_decl
("{full_internal_csignature} \{")
536 from_var
= nitni_visitor
.var_from_c
("from", from
)
537 from_var
= nitni_visitor
.box_extern
(from_var
, from
)
540 var check
= nitni_visitor
.type_test
(from_var
, to
, "FFI cast")
541 nitni_visitor
.add
("if (!{check}) \{")
542 nitni_visitor
.add_abort
("FFI cast failed")
543 nitni_visitor
.add
("\}")
546 recv_var
= nitni_visitor
.autobox
(from_var
, to
)
547 recv_var
= nitni_visitor
.unbox_extern
(recv_var
, to
)
549 nitni_visitor
.ret_to_c
(recv_var
, to
)
551 nitni_visitor
.add
("\}")
554 if from
.as_nullable
== to
then
555 # format A_as_nullable
556 ccu
.header_decl
.add
("#define {from.mangled_cname}_as_nullable {from.mangled_cname}_as_{to.mangled_cname}\n")
559 if from
== to
.as_nullable
then
560 # format A_as_nullable
561 ccu
.header_decl
.add
("#define {to.mangled_cname}_as_not_nullable {from.mangled_cname}_as_{to.mangled_cname}\n")