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
21 intrude import common_ffi
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")
49 nitni_ccu
.write_as_nitni
(self, v
.compiler
.modelbuilder
.compile_dir
)
51 for file
in nitni_ccu
.files
do
52 v
.compiler
.extern_bodies
.add
(new ExternCFile(file
, c_compiler_options
))
56 private fun ensure_compile_nitni_base
(v
: AbstractCompilerVisitor)
58 if nitni_ccu
!= null then return
60 nitni_ccu
= new CCompilationUnit
63 redef fun collect_linker_libs
65 var s
= c_linker_options
66 if s
.is_empty
then return null
67 var res
= new ArraySet[String]
72 private var compiled_callbacks
: Array[NitniCallback] = new Array[NitniCallback]
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
77 var compiled
= compiled_callbacks
.has
(cb
)
78 if not compiled
then compiled_callbacks
.add
(cb
)
83 redef class AExternPropdef
84 private fun compile_ffi_support_to_c
(v
: AbstractCompilerVisitor)
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
93 var csignature
= mpropdef
.mproperty
.build_csignature
(mclass_type
, mmodule
, "___impl", long_signature
, internal_call_context
)
94 v
.declare_once
("{csignature};")
97 amodule
.ensure_compile_ffi_wrapper
98 compile_ffi_method
(mmodule
)
100 # nitni - Compile missing callbacks
101 mmodule
.ensure_compile_nitni_base
(v
)
102 var ccu
= mmodule
.nitni_ccu
.as(not null)
104 for mtype
in foreign_callbacks
.types
do
105 if not mtype
.is_cprimitive
then
106 mtype
.compile_extern_type
(v
, ccu
)
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
)
114 for cb
in foreign_callbacks
.callbacks
do if mainmodule
.check_callback_compilation
(cb
) then
115 cb
.compile_extern_callback
(v
, ccu
)
118 for cb
in foreign_callbacks
.supers
do if mainmodule
.check_callback_compilation
(cb
) then
119 cb
.compile_extern_callback
(v
, ccu
)
122 for cb
in foreign_callbacks
.casts
do if mainmodule
.check_callback_compilation
(cb
) then
123 cb
.compile_extern_callbacks
(v
, ccu
)
126 # manage nitni callback set
127 mmodule
.foreign_callbacks
.join
(foreign_callbacks
)
131 redef class AExternMethPropdef
132 redef fun compile_to_c
(v
, mpropdef
, arguments
)
134 var mmodule
= mpropdef
.mclassdef
.mmodule
136 # if using the old native interface fallback on previous implementation
137 var nextern
= self.n_extern
138 if nextern
!= null then
143 mmodule
.uses_ffi
= true
145 var mclass_type
= mpropdef
.mclassdef
.bound_mtype
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
)
156 v
.adapt_signature
(mpropdef
, arguments
)
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
163 param_mtype
= mpropdef
.mclassdef
.mclass
.mclass_type
164 else param_mtype
= mpropdef
.msignature
.mparameters
[a-1
].mtype
166 param_mtype
= param_mtype
.anchor_to
(mmodule
, mclass_type
)
168 if param_mtype
.is_cprimitive
then
169 arguments_for_c
.add
(arg
.name
)
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}")
178 if recv_var
== null then
179 v
.add
("{externname}({arguments_for_c.join(", ")});")
181 assert return_mtype
!= null
182 if return_mtype
.is_cprimitive
then
183 v
.add
("{recv_var} = {externname}({arguments_for_c.join(", ")});")
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;")
192 compile_ffi_support_to_c
(v
)
196 redef class AExternInitPropdef
197 redef fun compile_to_c
(v
, mpropdef
, arguments
)
199 var mmodule
= mpropdef
.mclassdef
.mmodule
201 # if using the old native interface fallback on previous implementation
202 var nextern
= self.n_extern
203 if nextern
!= null then
208 mmodule
.uses_ffi
= true
210 var mclass_type
= mpropdef
.mclassdef
.bound_mtype
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
)
216 v
.adapt_signature
(mpropdef
, arguments
)
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
)
227 if param_mtype
.is_cprimitive
then
228 arguments_for_c
.add
(arg
.name
)
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}")
237 if return_mtype
.is_cprimitive
then
238 v
.add
("{recv_var} = {externname}({arguments_for_c.join(", ")});")
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;")
246 compile_ffi_support_to_c
(v
)
250 redef class CCompilationUnit
251 fun write_as_nitni
(mmodule
: MModule, compdir
: String)
253 var base_name
= "{mmodule.name}._nitni"
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")
259 var c_file
= "{base_name}.c"
260 write_body_to_file
( mmodule
, "{compdir}/{c_file}", ["\"{h_file}\
""] )
262 files
.add
( "{compdir}/{c_file}" )
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
270 if mtype
.is_cprimitive
then
271 return new RuntimeVariable(name
, mtype
, mtype
)
273 return new RuntimeVariable("{name}->value", mtype
, mtype
)
277 # Return a `RuntimeVarible` to C user code
278 private fun ret_to_c
(src
: RuntimeVariable, mtype
: MType)
280 if mtype
.is_cprimitive
then
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;")
292 private fun compile_extern_type
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
294 assert not is_cprimitive
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")
303 private fun compile_extern_helper_functions
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
305 # actually, we do not need to do anything when using the bohem garbage collector
308 var nitni_visitor
= v
.compiler
.new_visitor
309 ccu
.header_decl
.add
("#define {mangled_cname}_incr_ref(from) while(0)\{\}\n")
312 nitni_visitor
= v
.compiler
.new_visitor
313 ccu
.header_decl
.add
("#define {mangled_cname}_decr_ref(from) while(0)\{\}\n")
317 redef class MNullableType
318 redef fun compile_extern_helper_functions
(v
, ccu
)
322 var base_cname
= "null_{mtype.mangled_cname}"
323 var full_cname
= "NIT_NULL___{base_cname}"
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")
329 # In nitni files, #define friendly as extern
330 ccu
.header_decl
.add
("#define {base_cname} {full_cname}\n")
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
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
("\}")
350 private var is_already_compiled
= false # FIXME to remove, show above
353 redef class MExplicitCall
354 private fun compile_extern_callback
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
356 var mproperty
= mproperty
357 assert mproperty
isa MMethod
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")
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
)
369 nitni_visitor
.add_decl
("/* nitni callback for {mproperty.full_name} */")
370 nitni_visitor
.add_decl
("{csignature_blind} \{")
372 var vars
= new Array[RuntimeVariable]
373 var mtype
: MType = recv_mtype
375 if mproperty
.is_init
then
376 if recv_mtype
.mclass
.kind
== extern_kind
then
377 recv_var
= nitni_visitor
.new_var
(mtype
)
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};")
385 mtype
= mtype
.anchor_to
(v
.compiler
.mainmodule
, recv_mtype
)
386 recv_var
= nitni_visitor
.var_from_c
("recv", mtype
)
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
)
397 var ret_var
= nitni_visitor
.send
(mproperty
, vars
)
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
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
)
410 nitni_visitor
.add
("\}")
414 redef class MExplicitSuper
415 private fun compile_extern_callback
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
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
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")
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")
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
436 var csignature_blind
= mproperty
.build_csignature
(mclass_type
, v
.compiler
.mainmodule
, "___super", long_signature
, internal_call_context
)
438 nitni_visitor
.add_decl
("/* nitni callback to super for {mproperty.full_name} */")
439 nitni_visitor
.add_decl
("{csignature_blind} \{")
441 var vars
= new Array[RuntimeVariable]
443 var recv_var
= nitni_visitor
.var_from_c
("recv", mclass_type
)
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
)
452 var ret_var
= nitni_visitor
.supercall
(from
.as(MMethodDef), mclass_type
, vars
)
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
)
460 nitni_visitor
.add
("\}")
464 redef class MExplicitCast
465 private fun compile_extern_callbacks
(v
: AbstractCompilerVisitor, ccu
: CCompilationUnit)
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")
478 # In nitni files, #define friendly as extern
479 ccu
.header_decl
.add
("#define {check_cname} {v.compiler.mainmodule.name}___{check_cname}\n")
481 # Internally, implement internal function
482 var nitni_visitor
= v
.compiler
.new_visitor
483 nitni_visitor
.frame
= v
.frame
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} \{")
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};")
493 nitni_visitor
.add
("\}")
496 if from
== to
.as_nullable
then
498 ccu
.header_decl
.add
("#define {from.mangled_cname}_is_null !{from.mangled_cname}_is_a_{to.mangled_cname}\n")
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")
509 # In nitni files, #define friendly as extern
510 ccu
.header_decl
.add
("#define {cast_cname} {v.compiler.mainmodule.name}___{cast_cname}\n")
512 # Internally, implement internal function
513 nitni_visitor
= v
.compiler
.new_visitor
514 nitni_visitor
.frame
= v
.frame
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} \{")
520 from_var
= nitni_visitor
.var_from_c
("from", from
)
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
("\}")
529 recv_var
= nitni_visitor
.autobox
(from_var
, to
)
531 nitni_visitor
.ret_to_c
(recv_var
, to
)
533 nitni_visitor
.add
("\}")
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")
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")