1fa56e927038a738659c4b7189635c1a2c7992ac
[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 "recv"
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 # Make sure we have a .java file
169 mmodule.ensure_java_files
170
171 # Needed compiler and linker options
172 mmodule.insert_compiler_options
173
174 # Enable linking C callbacks to java native methods
175 mmodule.ensure_linking_callback_methods(ffi_ccu.as(not null))
176
177 # Java implementation code
178 var java_file = mmodule.java_file
179 assert java_file != null
180 var extern_java_file = java_file.write_to_files(compdir)
181 mmodule.ffi_files.add(extern_java_file)
182 end
183
184 var ffi_ccu: nullable CCompilationUnit = null # HACK
185
186 redef fun compile_callback(callback, mmodule, mainmodule, ccu)
187 do
188 ffi_ccu = ccu
189 callback.compile_callback_to_java(mmodule, mainmodule, ccu)
190 end
191 end
192
193 redef class MModule
194 private var callbacks_used_from_java = new ForeignCallbackSet
195
196 # Pure java class source file
197 private var java_file: nullable JavaClassTemplate = null
198
199 # Set up the templates of the Java implementation class
200 private fun ensure_java_files
201 do
202 if java_file != null then return
203
204 # Java implementation code
205 java_file = new JavaClassTemplate(impl_java_class_name)
206 end
207
208 # Compile C code to call JNI and link C callbacks implementations to Java extern methods
209 private fun ensure_linking_callback_methods(ccu: CCompilationUnit)
210 do
211 var callbacks = callbacks_used_from_java.callbacks
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("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/ -I $(JAVA_HOME)/include/linux/"
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 additional 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 developer can also customize the JNIEnv used by the FFI by redefining `Sys::jni_env`.
271 private fun insert_artificial_callbacks(toolcontext: ToolContext)
272 do
273 var fcc = foreign_callbacks
274
275 var modelbuilder = toolcontext.modelbuilder
276 var mmodule = mpropdef.mclassdef.mmodule
277
278 # We use callbacks from the C FFI since they will be called from generated C
279 var c_language_visitor = toolcontext.ffi_language_assignation_phase.as(FFILanguageAssignationPhase).c_language
280 if not mmodule.ffi_callbacks.keys.has(c_language_visitor) then
281 mmodule.ffi_callbacks[c_language_visitor] = new HashSet[NitniCallback]
282 end
283
284 # Pointer::sys
285 var pointer_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Pointer")
286 assert pointer_class != null
287 var pointer_sys_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, pointer_class.mclass_type, "sys")
288 assert pointer_sys_meth != null and pointer_sys_meth isa MMethod
289
290 var explicit_call = new MExplicitCall(pointer_class.mclass_type, pointer_sys_meth, mmodule)
291 fcc.callbacks.add(explicit_call)
292 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
293
294 # Sys::jni_env
295 var sys_class = modelbuilder.try_get_mclass_by_name(self, mmodule, "Sys")
296 assert sys_class != null
297 var sys_jni_env_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "jni_env")
298 if sys_jni_env_meth == null or not sys_jni_env_meth isa MMethod then
299 toolcontext.error(self.location, "Java FFI error: you must import the `java` module when using the FFI with Java")
300 return
301 end
302
303 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_env_meth, mmodule)
304 fcc.callbacks.add(explicit_call)
305 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
306
307 # Sys::load_jclass
308 var sys_jni_load_jclass_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "load_jclass")
309 assert sys_jni_load_jclass_meth != null
310 assert sys_jni_load_jclass_meth isa MMethod
311
312 explicit_call = new MExplicitCall(sys_class.mclass_type, sys_jni_load_jclass_meth, mmodule)
313 fcc.callbacks.add(explicit_call)
314 mmodule.ffi_callbacks[c_language_visitor].add(explicit_call)
315 explicit_call.fill_type_for(fcc, mmodule)
316 end
317 end
318
319 redef class AExternCodeBlock
320 # Is this code block in Java?
321 fun is_java: Bool do return is_default_java or (parent isa AModule and is_inner_java)
322
323 # Is this code block in Java, with the default mode? (On module blocks it targets the file header)
324 private fun is_default_java: Bool do return language_name != null and
325 language_name_lowered == "java"
326
327 # Is this code block in Java, and for a module block to generate in the class?
328 private fun is_inner_java: Bool do return language_name != null and
329 language_name_lowered == "java inner"
330 end
331
332 # Java class source template
333 class JavaClassTemplate
334 super Template
335
336 var java_class_name: String
337
338 var header = new Template
339 var class_content = new Template
340
341 fun write_to_files(compdir: String): ExternFile
342 do
343 var filename = "{java_class_name}.java"
344 var filepath = "{compdir}/{filename}"
345
346 write_to_file filepath
347
348 return new JavaFile(filename)
349 end
350
351 redef fun rendering
352 do
353 add header
354 add "\n"
355 add "public class {java_class_name} \{\n"
356 add class_content
357 add "\}"
358 end
359 end
360
361 # A generated Java source file, represent the corresponding Makefile rules
362 class JavaFile
363 super ExternFile
364
365 redef fun makefile_rule_name do return "{filename.basename(".java")}.class"
366 redef fun makefile_rule_content do return "javac {filename.basename("")} -d ."
367 redef fun add_to_jar do return true
368 end
369
370 # Context in pure Java code
371 private class JavaCallContext
372 super CallContext
373
374 redef fun name_mtype(mtype) do return mtype.java_type
375 end
376
377 # Context in C, when call are from normal C to JNI
378 private class ToJavaCallContext
379 super CallContext
380
381 redef fun cast_to(mtype, name) do return "({mtype.jni_type})({name})"
382 redef fun cast_from(mtype, name) do return "({mtype.cname})({name})"
383 redef fun name_mtype(mtype) do return mtype.jni_type
384 end
385
386 # Context in C, when call are from JNI to normal C
387 private class FromJavaCallContext
388 super CallContext
389
390 redef fun cast_to(mtype, name) do return "({mtype.cname})({name})"
391 redef fun cast_from(mtype, name) do return "({mtype.jni_type})({name})"
392 redef fun name_mtype(mtype) do return mtype.jni_type
393 end
394
395 # Foreign type attach to Nit extern Java classes
396 class ForeignJavaType
397 super ForeignType
398
399 var java_type: String
400 end
401
402 redef class NitniCallback
403 # Compile C and Java code to implement this callback
404 fun compile_callback_to_java(mmodule: MModule, mainmodule: MModule, ccu: CCompilationUnit) do end
405
406 # Returns the list of C functions to link with extern Java methods, as required
407 # to enable this callback from Java code.
408 #
409 # Return used by `MModule::ensure_linking_callback_methods`
410 #
411 # TODO we return an Array to support cast and other features like that
412 fun jni_methods_declaration(from_module: MModule): Array[String] do return new Array[String]
413 end
414
415 redef class MExplicitCall
416 redef fun compile_callback_to_java(mmodule, mainmodule, ccu)
417 do
418 if not mmodule.callbacks_used_from_java.callbacks.has(self) then return
419
420 var mproperty = mproperty
421 assert mproperty isa MMethod
422
423 # In C, indirection implementing the Java extern methods
424 var csignature = mproperty.build_c_implementation_signature(recv_mtype, mmodule, "___indirect", long_signature, from_java_call_context)
425 var cf = new CFunction("JNIEXPORT {csignature}")
426 cf.exprs.add "\t{mproperty.build_ccall(recv_mtype, mainmodule, null, long_signature, from_java_call_context, null)}\n"
427 ccu.add_local_function cf
428
429 # In Java, declare the extern method as a private static local method
430 var java_signature = mproperty.build_csignature(recv_mtype, mainmodule, null, short_signature, java_call_context)
431 mmodule.java_file.class_content.add "private native static {java_signature};\n"
432 end
433
434 redef fun jni_methods_declaration(from_mmodule)
435 do
436 var mproperty = mproperty
437 assert mproperty isa MMethod
438
439 var java_name = mproperty.build_cname(recv_mtype, from_mmodule, null, short_signature)
440 var jni_format = mproperty.build_jni_format(recv_mtype, from_mmodule)
441 var c_name = mproperty.build_cname(recv_mtype, from_mmodule, "___indirect", long_signature)
442
443 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
444 end
445 end
446
447 redef class MType
448
449 # Type name in Java
450 #
451 # * Primitives common to both languages use their Java primitive type
452 # * Nit extern Java classes are represented by their full Java type
453 # * Other Nit objects are represented by `int` in Java. It holds the
454 # pointer to the underlying C structure.
455 # TODO create static Java types to store and hide the pointer
456 private fun java_type: String do return "int"
457
458 # JNI type name (in C)
459 #
460 # So this is a C type, usually defined in `jni.h`
461 private fun jni_type: String do return "jint"
462
463 # JNI short type name (for signatures)
464 #
465 # Is used by `MMethod::build_jni_format` to pass a Java method signature
466 # to the JNI function `GetStaticMetodId`.
467 private fun jni_format: String do return "I"
468
469 # Type name appearing within JNI function names.
470 #
471 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
472 # This strategy is used by JNI to type the return of callbacks to Java.
473 private fun jni_signature_alt: String do return "Int"
474 end
475
476 redef class MClassType
477 redef fun java_type
478 do
479 var ftype = mclass.ftype
480 if ftype isa ForeignJavaType then return ftype.java_type.
481 replace('/', ".").replace('$', ".").replace(' ', "").replace('\n',"")
482 if mclass.name == "Bool" then return "boolean"
483 if mclass.name == "Char" then return "char"
484 if mclass.name == "Int" then return "long"
485 if mclass.name == "Float" then return "double"
486 return super
487 end
488
489 redef fun jni_type
490 do
491 var ftype = mclass.ftype
492 if ftype isa ForeignJavaType then return "jobject"
493 if mclass.name == "Bool" then return "jboolean"
494 if mclass.name == "Char" then return "jchar"
495 if mclass.name == "Int" then return "jlong"
496 if mclass.name == "Float" then return "jdouble"
497 return super
498 end
499
500 redef fun jni_format
501 do
502 var ftype = mclass.ftype
503 if ftype isa ForeignJavaType then
504 var jni_type = ftype.java_type.
505 replace('.', "/").replace(' ', "").replace('\n', "")
506
507 # Remove parameters of generic types
508 loop
509 var i = jni_type.last_index_of('<')
510 if i >= 0 then
511 var j = jni_type.index_of_from('>', i)
512 if j == -1 then
513 print "Error: missing closing '>' in extern Java type of \"{mclass.name}\""
514 exit 1
515 end
516 jni_type = jni_type.substring(0, i) +
517 jni_type.substring(j+1, jni_type.length)
518 else break
519 end
520
521 # Change `float[]` to `[float`
522 if jni_type.has('[') then
523 var depth = jni_type.chars.count('[')
524 var java_type = jni_type.replace("[]", "")
525 var short
526
527 if java_type == "boolean" then
528 short = "Z"
529 else if java_type == "byte" then
530 short = "B"
531 else if java_type == "char" then
532 short = "C"
533 else if java_type == "short" then
534 short = "S"
535 else if java_type == "int" then
536 short = "I"
537 else if java_type == "long" then
538 short = "J"
539 else if java_type == "float" then
540 short = "F"
541 else if java_type == "double" then
542 short = "D"
543 else
544 short = "L{java_type};"
545 end
546
547 return "["*depth + short
548 end
549
550 return "L{jni_type};"
551 end
552 if mclass.name == "Bool" then return "Z"
553 if mclass.name == "Char" then return "C"
554 if mclass.name == "Int" then return "J"
555 if mclass.name == "Float" then return "D"
556 return super
557 end
558
559 redef fun jni_signature_alt
560 do
561 var ftype = mclass.ftype
562
563 if ftype isa ForeignJavaType then return "Object"
564 if mclass.name == "Bool" then return "Boolean"
565 if mclass.name == "Char" then return "Char"
566 if mclass.name == "Int" then return "Long"
567 if mclass.name == "Float" then return "Double"
568 return super
569 end
570 end
571
572 redef class MMethod
573 # Returns the JNI signature format of this Nit method
574 #
575 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
576 # the JNI format `(ZIDLjava/lang/string;)V"
577 private fun build_jni_format(recv_mtype: MClassType, from_mmodule: MModule): String
578 do
579 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
580 var msignature = mmethoddef.msignature
581 var format = new Array[String]
582
583 format.add "("
584
585 # receiver
586 if not self.is_init then format.add recv_mtype.jni_format
587
588 # parameters
589 for p in msignature.mparameters do
590 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
591 format.add param_mtype.jni_format
592 end
593 format.add ")"
594
595 # return
596 if self.is_init then
597 format.add recv_mtype.jni_format
598 else
599 var return_mtype = msignature.return_mtype
600 if return_mtype != null then
601 return_mtype = return_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
602 format.add return_mtype.jni_format
603 else format.add "V"
604 end
605
606 return format.join("")
607 end
608
609 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
610 # implementing Java extern methods.
611 #
612 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
613 private fun build_c_implementation_signature(recv_mtype: MClassType, from_mmodule: MModule,
614 suffix: nullable String, length: SignatureLength, call_context: CallContext): String
615 do
616 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
617 var signature = mmethoddef.msignature
618 assert signature != null
619
620 var creturn_type
621 if self.is_init then
622 creturn_type = call_context.name_mtype(recv_mtype)
623 else if signature.return_mtype != null then
624 var ret_mtype = signature.return_mtype
625 ret_mtype = ret_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
626 creturn_type = call_context.name_mtype(ret_mtype)
627 else
628 creturn_type = "void"
629 end
630
631 var cname = build_cname(recv_mtype, from_mmodule, suffix, length)
632
633 var cparams = new List[String]
634
635 # This is different
636 cparams.add "JNIEnv *env"
637 cparams.add "jclass clazz"
638
639 if not self.is_init then
640 cparams.add "{call_context.name_mtype(recv_mtype)} recv"
641 end
642 for p in signature.mparameters do
643 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
644 cparams.add "{call_context.name_mtype(param_mtype)} {p.name}"
645 end
646
647 return "{creturn_type} {cname}( {cparams.join(", ")} )"
648 end
649 end
650
651 private fun java_call_context: JavaCallContext do return new JavaCallContext
652 private fun to_java_call_context: ToJavaCallContext do return new ToJavaCallContext
653 private fun from_java_call_context: FromJavaCallContext do return new FromJavaCallContext