Java FFI: extra_java_file annotation use full Java class name
[nit.git] / src / ffi / java.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013-2014 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 Java language
18 #
19 # TODO support callbacks to super and casts
20 module java
21
22 import extern_classes
23 import c
24 import c_compiler_options
25
26 redef class FFILanguageAssignationPhase
27 var java_language: FFILanguage = new JavaLanguage(self)
28 end
29
30 class JavaLanguage
31 super FFILanguage
32
33 redef fun identify_language(n) do return n.is_java
34
35 redef fun compile_module_block(block, ccu, mmodule)
36 do
37 mmodule.ensure_java_files
38 var java_file = mmodule.java_file
39 assert java_file != null
40
41 if block.is_inner_java then
42 java_file.class_content.add(block.code)
43 else java_file.header.add(block.code)
44 end
45
46 redef fun compile_extern_method(block, m, ccu, mmodule)
47 do
48 ffi_ccu = ccu
49 mmodule.ensure_java_files
50 var java_file = mmodule.java_file
51 assert java_file != null
52
53 var mclass_type = m.parent.as(AClassdef).mclass.mclass_type
54 var mmethodef = m.mpropdef
55 var mproperty = m.mpropdef.mproperty
56
57 # C function calling the Java method through JNI
58 var fc = new ExternCFunction(m, mmodule)
59
60 fc.exprs.add """
61 jclass java_class;
62 jmethodID java_meth_id;
63
64 // retrieve the current JVM
65 Sys sys = Pointer_sys(NULL);
66 JNIEnv *nit_ffi_jni_env = Sys_jni_env(sys);
67
68 // retrieve the implementation Java class
69 java_class = Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
70 if (java_class == NULL) {
71 PRINT_ERROR("Nit FFI with Java error: failed to load class.\\n");
72 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
73 exit(1);
74 }
75
76 // register callbacks (only once per Nit module)
77 if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
78 """
79
80 # Retrieve the Java implementation function id
81 var java_fun_name = mproperty.build_cname(mclass_type, mmodule, "___java_impl", long_signature)
82 var jni_format = mproperty.build_jni_format(mclass_type, mmodule)
83 fc.exprs.add """
84 // retreive the implementation static function
85 java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
86 if (java_meth_id == NULL) {
87 PRINT_ERROR("Nit FFI with Java error: Java implementation not found.\\n");
88 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
89 exit(1);
90 }
91 """
92
93 # Call the C Java implementation method from C
94 var signature = mmethodef.msignature
95 assert signature != null
96
97 var jni_signature_alt
98 var return_type
99 var params = new Array[String]
100 params.add "nit_ffi_jni_env"
101 params.add "java_class"
102 params.add "java_meth_id"
103
104 if mproperty.is_init then
105 jni_signature_alt = mclass_type.jni_signature_alt
106 return_type = mclass_type
107 else
108 params.add "self"
109 if signature.return_mtype != null then
110 var ret_mtype = signature.return_mtype
111 ret_mtype = ret_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
112 return_type = signature.return_mtype
113 jni_signature_alt = return_type.jni_signature_alt
114 else
115 jni_signature_alt = "Void"
116 return_type = null
117 end
118 end
119
120 for p in signature.mparameters do
121 var param_mtype = p.mtype
122 param_mtype = param_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
123 params.add(to_java_call_context.cast_to(param_mtype, p.name))
124 end
125
126 var cname = "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
127 var ccall
128 if return_type != null then
129 ccall = "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
130 else ccall = "{cname}({params.join(", ")});"
131
132 fc.exprs.add """
133 // execute implementation code
134 {{{ccall}}}
135 if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
136 PRINT_ERROR("Nit FFI with Java error: Exception after call.\\n");
137 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
138 exit(1);
139 }
140
141 (*nit_ffi_jni_env)->DeleteLocalRef(nit_ffi_jni_env, java_class);
142 """
143
144 if return_type != null then
145 fc.exprs.add "\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
146 end
147
148 ccu.add_exported_function( fc )
149
150 # Java implementation function in Java
151 var java_csig = mproperty.build_csignature(mclass_type, mmodule, "___java_impl", long_signature, java_call_context)
152 mmodule.java_file.class_content.add """
153 public static {{{java_csig}}} {
154 // from Nit FII at: {{{block.location}}}
155 {{{block.code}}}
156 }
157 """
158
159 mmodule.callbacks_used_from_java.join m.foreign_callbacks
160 end
161
162 redef fun compile_extern_class(block, m, ccu, mmodule) do end
163
164 redef fun get_ftype(block, m) do return new ForeignJavaType(block.code)
165
166 redef fun compile_to_files(mmodule, compdir)
167 do
168 var ffi_ccu = ffi_ccu
169 assert ffi_ccu != null
170
171 # Make sure we have a .java file
172 mmodule.ensure_java_files
173
174 # Needed compiler and linker options
175 mmodule.insert_compiler_options
176
177 # Enable linking C callbacks to java native methods
178 mmodule.ensure_linking_callback_methods(ffi_ccu)
179
180 # Java implementation code
181 var java_file = mmodule.java_file
182 assert java_file != null
183 var extern_java_file = java_file.write_to_files(compdir)
184 mmodule.ffi_files.add(extern_java_file)
185 end
186
187 var ffi_ccu: nullable CCompilationUnit = null # HACK
188
189 redef fun compile_callback(callback, mmodule, mainmodule, ccu)
190 do
191 ffi_ccu = ccu
192 callback.compile_callback_to_java(mmodule, mainmodule, ccu)
193 end
194 end
195
196 redef class MModule
197 private var callbacks_used_from_java = new ForeignCallbackSet
198
199 # Java source file extracted from user FFI code with generated structure
200 var java_file: nullable JavaClassTemplate = null
201
202 # Set up the templates of the Java implementation class
203 private fun ensure_java_files
204 do
205 if java_file != null then return
206
207 # Java implementation code
208 java_file = new JavaClassTemplate(impl_java_class_name)
209 end
210
211 # Compile C code to call JNI and link C callbacks implementations to Java extern methods
212 private fun ensure_linking_callback_methods(ccu: CCompilationUnit)
213 do
214 var callbacks = callbacks_used_from_java.callbacks
215 if callbacks.is_empty then
216 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 1;\n"
217 return
218 end
219
220 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 0;\n"
221
222 var jni_methods = new Array[String]
223 for cb in callbacks do
224 jni_methods.add_all(cb.jni_methods_declaration(self))
225 end
226 for cb in callbacks_used_from_java.types do
227 jni_methods.add_all(cb.jni_methods_declaration(self))
228 end
229
230 var cf = new CFunction("void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
231 cf.exprs.add """
232 nit_ffi_with_java_registered_natives = 1;
233
234 jint n_methods = {{{jni_methods.length}}};
235 JNINativeMethod methods[] = {
236 {{{jni_methods.join(",\n\t\t")}}}
237 };
238 jint res = (*env)->RegisterNatives(env, jclazz, methods, n_methods);
239 if (res != JNI_OK) {
240 PRINT_ERROR("RegisterNatives failed\\n");
241 (*env)->ExceptionDescribe(env);
242 exit(1);
243 }
244 """
245 ccu.add_local_function cf
246 end
247
248 # Tell the C compiler where to find jni.h and how to link with libjvm
249 private fun insert_compiler_options
250 do
251 cflags.add_one("", "-I $(JAVA_HOME)/include/ -I $(JAVA_HOME)/include/linux/")
252 end
253
254 # Name of the generated Java class where to store all implementation methods of this module
255 # as well as generated callbacks.
256 private fun impl_java_class_name: String do return "Nit_{name}"
257 end
258
259 redef class AMethPropdef
260 redef fun verify_nitni_callbacks(toolcontext)
261 do
262 super
263
264 var block = n_extern_code_block
265 if block != null and block.is_java then
266 insert_artificial_callbacks(toolcontext)
267 end
268 end
269
270 # Insert additional explicit calls to get the current `JNIEnv`
271 #
272 # This forces declaration of callbacks to Nit. The callbacks will be available in Java
273 # but will be used mainly by the FFI itself.
274 #
275 # The developer can also customize the JNIEnv used by the FFI by redefining `Sys::jni_env`.
276 private fun insert_artificial_callbacks(toolcontext: ToolContext)
277 do
278 var fcc = foreign_callbacks
279
280 var modelbuilder = toolcontext.modelbuilder
281 var mmodule = mpropdef.mclassdef.mmodule
282
283 # We use callbacks from the C FFI since they will be called from generated C
284 var c_language_visitor = toolcontext.ffi_language_assignation_phase.as(FFILanguageAssignationPhase).c_language
285 if not mmodule.ffi_callbacks.keys.has(c_language_visitor) then
286 mmodule.ffi_callbacks[c_language_visitor] = new HashSet[NitniCallback]
287 end
288
289 # Pointer::sys
290 var pointer_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Pointer")
291 assert pointer_class != null
292 var pointer_sys_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, pointer_class.mclass_type, "sys")
293 assert pointer_sys_meth != null and pointer_sys_meth isa MMethod
294
295 var explicit_call = new MExplicitCall(pointer_class.mclass_type, pointer_sys_meth, mmodule)
296 fcc.callbacks.add(explicit_call)
297 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
298
299 # Sys::jni_env
300 var sys_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Sys")
301 assert sys_class != null
302 var sys_jni_env_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "jni_env")
303 if sys_jni_env_meth == null or not sys_jni_env_meth isa MMethod then
304 toolcontext.error(self.location, "Java FFI Error: you must import the `java` module when using the FFI with Java")
305 return
306 end
307
308 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_env_meth, mmodule)
309 fcc.callbacks.add(explicit_call)
310 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
311
312 # Sys::load_jclass
313 var sys_jni_load_jclass_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "load_jclass")
314 assert sys_jni_load_jclass_meth != null
315 assert sys_jni_load_jclass_meth isa MMethod
316
317 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_load_jclass_meth, mmodule)
318 fcc.callbacks.add(explicit_call)
319 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
320 explicit_call.fill_type_for(fcc, mmodule)
321 end
322 end
323
324 redef class AExternCodeBlock
325 # Is this code block in Java?
326 fun is_java: Bool do return is_default_java or (parent isa AModule and is_inner_java)
327
328 # Is this code block in Java, with the default mode? (On module blocks it targets the file header)
329 private fun is_default_java: Bool do return language_name != null and
330 language_name_lowered == "java"
331
332 # Is this code block in Java, and for a module block to generate in the class?
333 private fun is_inner_java: Bool do return language_name != null and
334 language_name_lowered == "java inner"
335 end
336
337 # Java class source template
338 class JavaClassTemplate
339 super Template
340
341 var java_class_name: String
342
343 var header = new Template
344 var class_content = new Template
345
346 fun write_to_files(compdir: String): ExternFile
347 do
348 var filename = "{java_class_name}.java"
349 var filepath = compdir/filename
350
351 write_to_file filepath
352
353 return new JavaFile(filename)
354 end
355
356 redef fun rendering
357 do
358 add header
359 add "\n"
360 add "public class {java_class_name} \{\n"
361 add class_content
362 add "\}"
363 end
364 end
365
366 # A generated Java source file, represent the corresponding Makefile rules
367 class JavaFile
368 super ExternFile
369
370 # Full Java class name: package and class
371 fun full_name: String do return filename.basename(".java")
372
373 redef fun makefile_rule_name do return full_name.replace(".", "/") + ".class"
374 redef fun makefile_rule_content do return "javac {filename} -d ."
375 redef fun add_to_jar do return true
376 end
377
378 # Context in pure Java code
379 private class JavaCallContext
380 super CallContext
381
382 redef fun name_mtype(mtype) do return mtype.java_type
383 end
384
385 # Context in C, when call are from normal C to JNI
386 private class ToJavaCallContext
387 super CallContext
388
389 redef fun cast_to(mtype, name) do return "({mtype.jni_type})({name})"
390 redef fun cast_from(mtype, name) do return "({mtype.cname})({name})"
391 redef fun name_mtype(mtype) do return mtype.jni_type
392 end
393
394 # Context in C, when call are from JNI to normal C
395 private class FromJavaCallContext
396 super CallContext
397
398 redef fun cast_to(mtype, name) do return "({mtype.cname})({name})"
399 redef fun cast_from(mtype, name) do return "({mtype.jni_type})({name})"
400 redef fun name_mtype(mtype) do return mtype.jni_type
401 end
402
403 # Foreign type attach to Nit extern Java classes
404 class ForeignJavaType
405 super ForeignType
406
407 var java_type: String
408 end
409
410 redef class NitniCallback
411 # Compile C and Java code to implement this callback
412 fun compile_callback_to_java(mmodule: MModule, mainmodule: MModule, ccu: CCompilationUnit) do end
413
414 # Returns the list of C functions to link with extern Java methods, as required
415 # to enable this callback from Java code.
416 #
417 # Return used by `MModule::ensure_linking_callback_methods`
418 #
419 # TODO we return an Array to support cast and other features like that
420 fun jni_methods_declaration(from_module: MModule): Array[String] do return new Array[String]
421 end
422
423 redef class MExplicitCall
424 redef fun compile_callback_to_java(mmodule, mainmodule, ccu)
425 do
426 if not mmodule.callbacks_used_from_java.callbacks.has(self) then return
427
428 var mproperty = mproperty
429 assert mproperty isa MMethod
430
431 # In C, indirection implementing the Java extern methods
432 var csignature = mproperty.build_c_implementation_signature(recv_mtype, mmodule, "___indirect", long_signature, from_java_call_context)
433 var cf = new CFunction("JNIEXPORT {csignature}")
434 cf.exprs.add "\t{mproperty.build_ccall(recv_mtype, mainmodule, null, long_signature, from_java_call_context, null)}\n"
435 ccu.add_non_static_local_function cf
436
437 # In Java, declare the extern method as a private static local method
438 var java_signature = mproperty.build_csignature(recv_mtype, mainmodule, null, short_signature, java_call_context)
439 mmodule.java_file.class_content.add "private native static {java_signature};\n"
440 end
441
442 redef fun jni_methods_declaration(from_mmodule)
443 do
444 var mproperty = mproperty
445 assert mproperty isa MMethod
446
447 var java_name = mproperty.build_cname(recv_mtype, from_mmodule, null, short_signature)
448 var jni_format = mproperty.build_jni_format(recv_mtype, from_mmodule)
449 var c_name = mproperty.build_cname(recv_mtype, from_mmodule, "___indirect", long_signature)
450
451 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
452 end
453 end
454
455 redef class MType
456
457 # Type name in Java
458 #
459 # * Primitives common to both languages use their Java primitive type
460 # * Nit extern Java classes are represented by their full Java type
461 # * Other Nit objects are represented by `int` in Java. It holds the
462 # pointer to the underlying C structure.
463 # TODO create static Java types to store and hide the pointer
464 private fun java_type: String do return "int"
465
466 # JNI type name (in C)
467 #
468 # So this is a C type, usually defined in `jni.h`
469 private fun jni_type: String do return "long"
470
471 # JNI short type name (for signatures)
472 #
473 # Is used by `MMethod::build_jni_format` to pass a Java method signature
474 # to the JNI function `GetStaticMetodId`.
475 private fun jni_format: String do return "I"
476
477 # Type name appearing within JNI function names.
478 #
479 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
480 # This strategy is used by JNI to type the return of callbacks to Java.
481 private fun jni_signature_alt: String do return "Int"
482
483 redef fun compile_callback_to_java(mmodule, mainmodule, ccu)
484 do
485 var java_file = mmodule.java_file
486 if java_file == null then return
487
488 for variation in ["incr", "decr"] do
489 var friendly_name = "{mangled_cname}_{variation}_ref"
490
491 # C
492 var csignature = "void {mmodule.impl_java_class_name}_{friendly_name}(JNIEnv *env, jclass clazz, jint object)"
493 var cf = new CFunction("JNIEXPORT {csignature}")
494 cf.exprs.add "\tnitni_global_ref_{variation}((void*)(long)object);"
495 ccu.add_non_static_local_function cf
496
497 # Java
498 java_file.class_content.add "private native static void {friendly_name}(int object);\n"
499 end
500 end
501
502 redef fun jni_methods_declaration(from_mmodule)
503 do
504 var arr = new Array[String]
505 for variation in ["incr", "decr"] do
506 var friendly_name = "{mangled_cname}_{variation}_ref"
507 var jni_format = "(I)V"
508 var cname = "{from_mmodule.impl_java_class_name}_{friendly_name}"
509 arr.add """{"{{{friendly_name}}}", "{{{jni_format}}}", {{{cname}}}}"""
510 end
511
512 return arr
513 end
514 end
515
516 redef class MClassType
517 redef fun java_type
518 do
519 var ftype = mclass.ftype
520 if ftype isa ForeignJavaType then return ftype.java_type.
521 replace('/', ".").replace('$', ".").replace(' ', "").replace('\n',"")
522 if mclass.name == "Bool" then return "boolean"
523 if mclass.name == "Char" then return "int"
524 if mclass.name == "Int" then return "long"
525 if mclass.name == "Float" then return "double"
526 if mclass.name == "Byte" then return "byte"
527 if mclass.name == "Int8" then return "byte"
528 if mclass.name == "Int16" then return "short"
529 if mclass.name == "UInt16" then return "short"
530 if mclass.name == "Int32" then return "int"
531 if mclass.name == "UInt32" then return "int"
532 return super
533 end
534
535 redef fun jni_type
536 do
537 var ftype = mclass.ftype
538 if ftype isa ForeignJavaType then return "jobject"
539 if mclass.name == "Bool" then return "jboolean"
540 if mclass.name == "Char" then return "jint"
541 if mclass.name == "Int" then return "jlong"
542 if mclass.name == "Float" then return "jdouble"
543 if mclass.name == "Byte" then return "jbyte"
544 if mclass.name == "Int8" then return "jbyte"
545 if mclass.name == "Int16" then return "jshort"
546 if mclass.name == "UInt16" then return "jshort"
547 if mclass.name == "Int32" then return "jint"
548 if mclass.name == "UInt32" then return "jint"
549 return super
550 end
551
552 redef fun jni_format
553 do
554 var ftype = mclass.ftype
555 if ftype isa ForeignJavaType then
556 var jni_type = ftype.java_type.
557 replace('.', "/").replace(' ', "").replace('\n', "")
558
559 # Remove parameters of generic types
560 loop
561 var i = jni_type.last_index_of('<')
562 if i >= 0 then
563 var j = jni_type.index_of_from('>', i)
564 if j == -1 then
565 print "Error: missing closing '>' in extern Java type of \"{mclass.name}\""
566 exit 1
567 end
568 jni_type = jni_type.substring(0, i) +
569 jni_type.substring(j+1, jni_type.length)
570 else break
571 end
572
573 # Change `float[]` to `[float`
574 if jni_type.has('[') then
575 var depth = jni_type.chars.count('[')
576 var java_type = jni_type.replace("[]", "")
577 var short
578
579 if java_type == "boolean" then
580 short = "Z"
581 else if java_type == "byte" then
582 short = "B"
583 else if java_type == "char" then
584 short = "C"
585 else if java_type == "short" then
586 short = "S"
587 else if java_type == "int" then
588 short = "I"
589 else if java_type == "long" then
590 short = "J"
591 else if java_type == "float" then
592 short = "F"
593 else if java_type == "double" then
594 short = "D"
595 else
596 short = "L{java_type};"
597 end
598
599 return "["*depth + short
600 end
601
602 return "L{jni_type};"
603 end
604 if mclass.name == "Bool" then return "Z"
605 if mclass.name == "Char" then return "I"
606 if mclass.name == "Int" then return "J"
607 if mclass.name == "Float" then return "D"
608 if mclass.name == "Byte" then return "B"
609 if mclass.name == "Int8" then return "B"
610 if mclass.name == "Int16" then return "S"
611 if mclass.name == "UInt16" then return "S"
612 if mclass.name == "Int32" then return "I"
613 if mclass.name == "UInt32" then return "I"
614 return super
615 end
616
617 redef fun jni_signature_alt
618 do
619 var ftype = mclass.ftype
620
621 if ftype isa ForeignJavaType then return "Object"
622 if mclass.name == "Bool" then return "Boolean"
623 if mclass.name == "Char" then return "Int"
624 if mclass.name == "Int" then return "Long"
625 if mclass.name == "Float" then return "Double"
626 if mclass.name == "Byte" then return "Byte"
627 if mclass.name == "Int8" then return "Byte"
628 if mclass.name == "Int16" then return "Short"
629 if mclass.name == "UInt16" then return "Short"
630 if mclass.name == "Int32" then return "Int"
631 if mclass.name == "UInt32" then return "Int"
632 return super
633 end
634 end
635
636 redef class MMethod
637 # Returns the JNI signature format of this Nit method
638 #
639 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
640 # the JNI format `(ZIDLjava/lang/string;)V"
641 private fun build_jni_format(recv_mtype: MClassType, from_mmodule: MModule): String
642 do
643 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
644 var msignature = mmethoddef.msignature
645 var format = new Array[String]
646
647 format.add "("
648
649 # receiver
650 if not self.is_init then format.add recv_mtype.jni_format
651
652 # parameters
653 for p in msignature.mparameters do
654 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
655 format.add param_mtype.jni_format
656 end
657 format.add ")"
658
659 # return
660 if self.is_init then
661 format.add recv_mtype.jni_format
662 else
663 var return_mtype = msignature.return_mtype
664 if return_mtype != null then
665 return_mtype = return_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
666 format.add return_mtype.jni_format
667 else format.add "V"
668 end
669
670 return format.join
671 end
672
673 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
674 # implementing Java extern methods.
675 #
676 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
677 private fun build_c_implementation_signature(recv_mtype: MClassType, from_mmodule: MModule,
678 suffix: nullable String, length: SignatureLength, call_context: CallContext): String
679 do
680 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
681 var signature = mmethoddef.msignature
682 assert signature != null
683
684 var creturn_type
685 if self.is_init then
686 creturn_type = call_context.name_mtype(recv_mtype)
687 else if signature.return_mtype != null then
688 var ret_mtype = signature.return_mtype
689 ret_mtype = ret_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
690 creturn_type = call_context.name_mtype(ret_mtype)
691 else
692 creturn_type = "void"
693 end
694
695 var cname = build_cname(recv_mtype, from_mmodule, suffix, length)
696
697 var cparams = new List[String]
698
699 # This is different
700 cparams.add "JNIEnv *env"
701 cparams.add "jclass clazz"
702
703 if not self.is_init then
704 cparams.add "{call_context.name_mtype(recv_mtype)} self"
705 end
706 for p in signature.mparameters do
707 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
708 cparams.add "{call_context.name_mtype(param_mtype)} {p.name}"
709 end
710
711 return "{creturn_type} {cname}( {cparams.join(", ")} )"
712 end
713 end
714
715 private fun java_call_context: JavaCallContext do return new JavaCallContext
716 private fun to_java_call_context: ToJavaCallContext do return new ToJavaCallContext
717 private fun from_java_call_context: FromJavaCallContext do return new FromJavaCallContext
718
719 redef class CCompilationUnit
720 # Similar to `add_local_function` but not `static`
721 #
722 # Used when the signature contains a visibility attribute.
723 private fun add_non_static_local_function(c_function: CFunction)
724 do
725 body_decl.add c_function.signature
726 body_decl.add ";\n"
727
728 body_impl.add "\n"
729 body_impl.add c_function.to_writer
730 end
731 end