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