ffi/java: use existing Set of callbacks per language and modules
[nit.git] / src / common_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, nmodule)
36 do
37 nmodule.ensure_java_files
38 var java_file = nmodule.java_file
39 assert java_file != null
40
41 java_file.header.add(block.code)
42 end
43
44 redef fun compile_extern_method(block, m, ccu, nmodule)
45 do
46 ffi_ccu = ccu
47 nmodule.ensure_java_files
48 var java_file = nmodule.java_file
49 assert java_file != null
50
51 var mmodule = nmodule.mmodule.as(not null)
52 var mclass_type = m.parent.as(AClassdef).mclass.mclass_type
53 var mmethodef = m.mpropdef
54 var mproperty = m.mpropdef.mproperty
55
56 # C function calling the Java method through JNI
57 var fc = new ExternCFunction(m, mmodule)
58
59 fc.exprs.add """
60 jclass java_class;
61 jmethodID java_meth_id;
62
63 // retrieve the current JVM
64 Sys sys = {{{mmodule.name}}}___Pointer_sys(NULL);
65 JNIEnv *nit_ffi_jni_env = {{{mmodule.name}}}___Sys_jni_env(sys);
66
67 // retrieve the implementation Java class
68 java_class = {{{mmodule.name}}}___Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
69 if (java_class == NULL) {
70 fprintf(stderr, "Nit FFI with Java error: failed to load class.\\n");
71 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
72 exit(1);
73 }
74
75 // register callbacks (only once per Nit module)
76 if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
77 """
78
79 # Retrieve the Java implementation function id
80 var java_fun_name = mproperty.build_cname(mclass_type, mmodule, "___java_impl", long_signature)
81 var jni_format = mproperty.build_jni_format(mclass_type, mmodule)
82 fc.exprs.add """
83 // retreive the implementation static function
84 java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
85 if (java_meth_id == NULL) {
86 fprintf(stderr, "Nit FFI with Java error: Java implementation not found.\\n");
87 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
88 exit(1);
89 }
90 """
91
92 # Call the C Java implementation method from C
93 var signature = mmethodef.msignature
94 assert signature != null
95
96 var jni_signature_alt
97 var return_type
98 var c_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 c_return_type = mclass_type.cname
108 else
109 params.add "recv"
110 if signature.return_mtype != null then
111 var ret_mtype = signature.return_mtype
112 ret_mtype = ret_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
113 return_type = signature.return_mtype
114 c_return_type = mclass_type.cname
115 jni_signature_alt = return_type.jni_signature_alt
116 else
117 jni_signature_alt = "Void"
118 return_type = null
119 c_return_type = null
120 end
121 end
122
123 for p in signature.mparameters do params.add(p.name)
124
125 var cname = "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
126 var ccall
127 if return_type != null then
128 ccall = "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
129 else ccall = "{cname}({params.join(", ")});"
130
131 fc.exprs.add """
132 // execute implementation code
133 {{{ccall}}}
134 if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
135 fprintf(stderr, "Nit FFI with Java error: Exception after call.\\n");
136 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
137 exit(1);
138 }
139 """
140
141 if return_type != null then
142 fc.exprs.add "\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
143 end
144
145 ccu.add_exported_function( fc )
146
147 # Java implementation function in Java
148 var java_csig = mproperty.build_csignature(mclass_type, mmodule, "___java_impl", long_signature, java_call_context)
149 nmodule.java_file.class_content.add """
150 public static {{{java_csig}}} {
151 // from Nit FII at: {{{block.location}}}
152 {{{block.code}}}
153 }
154 """
155 end
156
157 redef fun compile_extern_class(block, m, ccu, nmodule) do end
158
159 redef fun get_ftype(block, m) do return new ForeignJavaType(block.code)
160
161 redef fun compile_to_files(nmodule, compdir)
162 do
163 # Make sure we have a .java file
164 nmodule.ensure_java_files
165
166 # Needed compiler and linker options
167 nmodule.insert_compiler_options
168
169 # Enable linking C callbacks to java native methods
170 nmodule.ensure_linking_callback_methods(ffi_ccu, nmodule.ffi_callbacks[self])
171
172 # Java implementation code
173 var java_file = nmodule.java_file
174 assert java_file != null
175 var extern_java_file = java_file.write_to_files(compdir)
176 nmodule.ffi_files.add(extern_java_file)
177 end
178
179 var ffi_ccu: CCompilationUnit # HACK
180
181 redef fun compile_callback(callback, nmodule, mainmodule, ccu)
182 do
183 ffi_ccu = ccu
184 callback.compile_callback_to_java(nmodule, ccu)
185 end
186 end
187
188 redef class AModule
189
190 # Pure java class source file
191 private var java_file: nullable JavaClassTemplate = null
192
193 # Set up the templates of the Java implementation class
194 private fun ensure_java_files
195 do
196 if java_file != null then return
197
198 # Java implementation code
199 java_file = new JavaClassTemplate(mmodule.impl_java_class_name)
200 end
201
202 # Compile C code to call JNI and link C callbacks implementations to Java extern methods
203 private fun ensure_linking_callback_methods(ccu: CCompilationUnit, callbacks: Set[NitniCallback])
204 do
205 if callbacks.is_empty then
206 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 1;\n"
207 return
208 end
209
210 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 0;\n"
211
212 var jni_methods = new Array[String]
213 for cb in callbacks do
214 jni_methods.add_all(cb.jni_methods_declaration(mmodule.as(not null)))
215 end
216
217 var cf = new CFunction("static void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
218 cf.exprs.add """
219 nit_ffi_with_java_registered_natives = 1;
220
221 jint n_methods = {{{jni_methods.length}}};
222 JNINativeMethod methods[] = {
223 {{{jni_methods.join(",\n\t\t")}}}
224 };
225 jint res = (*env)->RegisterNatives(env, jclazz, methods, n_methods);
226 if (res != JNI_OK) {
227 fprintf(stderr, "RegisterNatives failed\\n");
228 (*env)->ExceptionDescribe(env);
229 exit(1);
230 }
231 """
232 ccu.add_local_function cf
233 end
234
235 # Tell the C compiler where to find jni.h and how to link with libjvm
236 private fun insert_compiler_options
237 do
238 mmodule.c_compiler_options = "{mmodule.c_compiler_options} -I $(JAVA_HOME)/include/"
239 mmodule.c_linker_options = "{mmodule.c_linker_options} -L $(JNI_LIB_PATH) -ljvm"
240 end
241 end
242
243 redef class MModule
244 # Name of the generated Java class where to store all implementation methods of this module
245 # as well as generated callbacks.
246 private fun impl_java_class_name: String do return "NitFFIWithJava_{name}"
247 end
248
249 redef class AExternPropdef
250 redef fun verify_nitni_callbacks(toolcontext)
251 do
252 super
253
254 var block = n_extern_code_block
255 if block != null and block.is_java then
256 insert_artificial_callbacks(toolcontext)
257 end
258 end
259
260 # Insert additionnal explicit calls to get the current `JNIEnv`
261 #
262 # This forces declaration of callbacks to Nit. The callbacks will be available in Java
263 # but will be used mainly by the FFI itself.
264 #
265 # The developper can aso customize the JNIEnv used by the FFI by redefing `Sys::jni_env`.
266 private fun insert_artificial_callbacks(toolcontext: ToolContext)
267 do
268 var fcc = foreign_callbacks
269 assert fcc != null
270
271 var modelbuilder = toolcontext.modelbuilder
272 var mmodule = mpropdef.mclassdef.mmodule
273
274 # Pointer::sys
275 var pointer_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Pointer")
276 assert pointer_class != null
277 var pointer_sys_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, pointer_class.mclass_type, "sys")
278 assert pointer_sys_meth != null and pointer_sys_meth isa MMethod
279
280 var explicit_call = new MExplicitCall(pointer_class.mclass_type, pointer_sys_meth, mmodule)
281 fcc.callbacks.add(explicit_call)
282 explicit_call.fill_type_for(fcc, mmodule)
283
284 # Sys::jni_env
285 var sys_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Sys")
286 assert sys_class != null
287 var sys_jni_env_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "jni_env")
288 assert sys_jni_env_meth != null
289 assert sys_jni_env_meth isa MMethod
290
291 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_env_meth, mmodule)
292 fcc.callbacks.add(explicit_call)
293 explicit_call.fill_type_for(fcc, mmodule)
294
295 # Sys::load_jclass
296 var sys_jni_load_jclass_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "load_jclass")
297 assert sys_jni_load_jclass_meth != null
298 assert sys_jni_load_jclass_meth isa MMethod
299
300 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_load_jclass_meth, mmodule)
301 fcc.callbacks.add(explicit_call)
302 explicit_call.fill_type_for(fcc, mmodule)
303 end
304 end
305
306 redef class AExternCodeBlock
307 fun is_java : Bool do return language_name != null and
308 language_name_lowered == "java"
309 end
310
311 # Java class source template
312 class JavaClassTemplate
313 super Template
314
315 var java_class_name: String
316 init(name: String) do self.java_class_name = name
317
318 var header = new Template
319 var class_content = new Template
320
321 fun write_to_files(compdir: String): ExternFile
322 do
323 var filename = "{java_class_name}.java"
324 var filepath = "{compdir}/{filename}"
325
326 write_to_file filepath
327
328 return new JavaFile(filename)
329 end
330
331 redef fun rendering
332 do
333 add header
334 add "\n"
335 add "public class {java_class_name} \{\n"
336 add class_content
337 add "\}"
338 end
339 end
340
341 # A generated Java source file, represent the corresponding Makefile rules
342 class JavaFile
343 super ExternFile
344
345 redef fun makefile_rule_name do return "{filename.basename(".java")}.class"
346 redef fun makefile_rule_content do return "javac {filename} -d ."
347 redef fun add_to_jar do return true
348 end
349
350 # Context in pure Java code
351 private class JavaCallContext
352 super CallContext
353
354 redef fun name_mtype(mtype) do return mtype.java_type
355 end
356
357 # Context in C, when call are from normal C to JNI
358 private class ToJavaCallContext
359 super CallContext
360
361 redef fun cast_to(mtype, name) do return "({mtype.jni_type})({name})"
362 redef fun cast_from(mtype, name) do return "({mtype.cname})({name})"
363 redef fun name_mtype(mtype) do return mtype.jni_type
364 end
365
366 # Context in C, when call are from JNI to normal C
367 private class FromJavaCallContext
368 super CallContext
369
370 redef fun cast_to(mtype, name) do return "({mtype.cname})({name})"
371 redef fun cast_from(mtype, name) do return "({mtype.jni_type})({name})"
372 redef fun name_mtype(mtype) do return mtype.jni_type
373 end
374
375 # Foreign type attach to Nit extern Java classes
376 class ForeignJavaType
377 super ForeignType
378
379 var java_type: String
380 init (java_type: String) do self.java_type = java_type
381 end
382
383 redef class NitniCallback
384 # Compile C and Java code to implement this callback
385 fun compile_callback_to_java(nmodule: AModule, ccu: CCompilationUnit) do end
386
387 # Returns the list of C functions to link with extern Java methods, as required
388 # to enable this callback from Java code.
389 #
390 # Return used by `AModule::ensure_linking_callback_methods`
391 #
392 # TODO we return an Array to support cast and other features like that
393 fun jni_methods_declaration(from_module: MModule): Array[String] do return new Array[String]
394 end
395
396 redef class MExplicitCall
397 redef fun compile_callback_to_java(nmodule, ccu)
398 do
399 var mproperty = mproperty
400 assert mproperty isa MMethod
401 var mmodule = nmodule.mmodule.as(not null)
402
403 # In C, indirection implementing the Java extern methods
404 var csignature = mproperty.build_c_implementation_signature(recv_mtype, mmodule, "___indirect", long_signature, from_java_call_context)
405 var cf = new CFunction("JNIEXPORT {csignature}")
406 cf.exprs.add "\t{mproperty.build_ccall(recv_mtype, mmodule, null, long_signature, from_java_call_context, null)}\n"
407 ccu.add_local_function cf
408
409 # In Java, declare the extern method as a private static local method
410 var java_signature = mproperty.build_csignature(recv_mtype, mmodule, null, short_signature, java_call_context)
411 nmodule.java_file.class_content.add "private native static {java_signature};\n"
412 end
413
414 redef fun jni_methods_declaration(from_mmodule)
415 do
416 var mproperty = mproperty
417 assert mproperty isa MMethod
418
419 var java_name = mproperty.build_cname(recv_mtype, from_mmodule, null, short_signature)
420 var jni_format = mproperty.build_jni_format(recv_mtype, from_mmodule)
421 var c_name = mproperty.build_cname(recv_mtype, from_mmodule, "___indirect", long_signature)
422
423 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
424 end
425 end
426
427 redef class MType
428
429 # Type name in Java
430 #
431 # * Primitives common to both languages use their Java primitive type
432 # * Nit extern Java classes are reprensented by their full Java type
433 # * Other Nit objects are represented by `int` in Java. It holds the
434 # pointer to the underlying C structure.
435 # TODO create static Java types to store and hide the pointer
436 private fun java_type: String do return "int"
437
438 # JNI type name (in C)
439 #
440 # So this is a C type, usually defined in `jni.h`
441 private fun jni_type: String do return "jint"
442
443 # JNI short type name (for signatures)
444 #
445 # Is used by `MMethod::build_jni_format` to pass a Java method signature
446 # to the JNI function `GetStaticMetodId`.
447 private fun jni_format: String do return "I"
448
449 # Type name appearing within JNI function names.
450 #
451 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
452 # This strategy is used by JNI to type the return of callbacks to Java.
453 private fun jni_signature_alt: String do return "Int"
454 end
455
456 redef class MClassType
457 redef fun java_type
458 do
459 var ftype = mclass.ftype
460 if ftype isa ForeignJavaType then return ftype.java_type
461 if mclass.name == "Bool" then return "boolean"
462 if mclass.name == "Char" then return "char"
463 if mclass.name == "Int" then return "int"
464 if mclass.name == "Float" then return "double"
465 return super
466 end
467
468 redef fun jni_type
469 do
470 var ftype = mclass.ftype
471 if ftype isa ForeignJavaType then return "jobject"
472 if mclass.name == "Bool" then return "jboolean"
473 if mclass.name == "Char" then return "jchar"
474 if mclass.name == "Int" then return "jint"
475 if mclass.name == "Float" then return "jdouble"
476 return super
477 end
478
479 redef fun jni_format
480 do
481 var ftype = mclass.ftype
482 if ftype isa ForeignJavaType then return "L{ftype.java_type.replace('.', "/").replace(' ', "")};"
483 if mclass.name == "Bool" then return "Z"
484 if mclass.name == "Char" then return "C"
485 if mclass.name == "Int" then return "I"
486 if mclass.name == "Float" then return "D"
487 return super
488 end
489
490 redef fun jni_signature_alt
491 do
492 var ftype = mclass.ftype
493 if ftype isa ForeignJavaType then return "Object"
494 if mclass.name == "Bool" then return "Bool"
495 if mclass.name == "Char" then return "Char"
496 if mclass.name == "Int" then return "Int"
497 if mclass.name == "Float" then return "Double"
498 return super
499 end
500 end
501
502 redef class MMethod
503 # Returns the JNI signature format of this Nit method
504 #
505 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
506 # the JNI format `(ZIDLjava/lang/string;)V"
507 private fun build_jni_format(recv_mtype: MClassType, from_mmodule: MModule): String
508 do
509 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
510 var msignature = mmethoddef.msignature
511 var format = new Array[String]
512
513 format.add "("
514
515 # receiver
516 if not self.is_init then format.add recv_mtype.jni_format
517
518 # parameters
519 for p in msignature.mparameters do
520 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
521 format.add param_mtype.jni_format
522 end
523 format.add ")"
524
525 # return
526 if self.is_init then
527 format.add recv_mtype.jni_format
528 else
529 var return_mtype = msignature.return_mtype
530 if return_mtype != null then
531 format.add return_mtype.jni_format
532 else format.add "V"
533 end
534
535 return format.join("")
536 end
537
538 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
539 # implementing Java extern methods.
540 #
541 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
542 private fun build_c_implementation_signature(recv_mtype: MClassType, from_mmodule: MModule,
543 suffix: nullable String, length: SignatureLength, call_context: CallContext): String
544 do
545 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
546 var signature = mmethoddef.msignature
547 assert signature != null
548
549 var creturn_type
550 if self.is_init then
551 creturn_type = call_context.name_mtype(recv_mtype)
552 else if signature.return_mtype != null then
553 var ret_mtype = signature.return_mtype
554 ret_mtype = ret_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
555 creturn_type = call_context.name_mtype(ret_mtype)
556 else
557 creturn_type = "void"
558 end
559
560 var cname = build_cname(recv_mtype, from_mmodule, suffix, length)
561
562 var cparams = new List[String]
563
564 # This is different
565 cparams.add "JNIEnv *env"
566 cparams.add "jclass clazz"
567
568 if not self.is_init then
569 cparams.add "{call_context.name_mtype(recv_mtype)} recv"
570 end
571 for p in signature.mparameters do
572 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
573 cparams.add "{call_context.name_mtype(param_mtype)} {p.name}"
574 end
575
576 return "{creturn_type} {cname}( {cparams.join(", ")} )"
577 end
578 end
579
580 private fun java_call_context: JavaCallContext do return new JavaCallContext
581 private fun to_java_call_context: ToJavaCallContext do return new ToJavaCallContext
582 private fun from_java_call_context: FromJavaCallContext do return new FromJavaCallContext