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