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