1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013-2014 Alexis Laferrière <alexis.laf@xymus.net>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # FFI support for the Java language
19 # TODO support callbacks to super and casts
24 import c_compiler_options
26 redef class FFILanguageAssignationPhase
27 var java_language
: FFILanguage = new JavaLanguage(self)
33 redef fun identify_language
(n
) do return n
.is_java
35 redef fun compile_module_block
(block
, ccu
, mmodule
)
37 mmodule
.ensure_java_files
38 var java_file
= mmodule
.java_file
39 assert java_file
!= null
41 java_file
.header
.add
(block
.code
)
44 redef fun compile_extern_method
(block
, m
, ccu
, mmodule
)
47 mmodule
.ensure_java_files
48 var java_file
= mmodule
.java_file
49 assert java_file
!= null
51 var mclass_type
= m
.parent
.as(AClassdef).mclass
.mclass_type
52 var mmethodef
= m
.mpropdef
53 var mproperty
= m
.mpropdef
.mproperty
55 # C function calling the Java method through JNI
56 var fc
= new ExternCFunction(m
, mmodule
)
60 jmethodID java_meth_id;
62 // retrieve the current JVM
63 Sys sys = Pointer_sys(NULL);
64 JNIEnv *nit_ffi_jni_env = Sys_jni_env(sys);
66 // retrieve the implementation Java class
67 java_class = Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
68 if (java_class == NULL) {
69 PRINT_ERROR("Nit FFI with Java error: failed to load class.\\n");
70 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
74 // register callbacks (only once per Nit module)
75 if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
78 # Retrieve the Java implementation function id
79 var java_fun_name
= mproperty
.build_cname
(mclass_type
, mmodule
, "___java_impl", long_signature
)
80 var jni_format
= mproperty
.build_jni_format
(mclass_type
, mmodule
)
82 // retreive the implementation static function
83 java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
84 if (java_meth_id == NULL) {
85 PRINT_ERROR("Nit FFI with Java error: Java implementation not found.\\n");
86 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
91 # Call the C Java implementation method from C
92 var signature
= mmethodef
.msignature
93 assert signature
!= null
98 var params
= new Array[String]
99 params
.add
"nit_ffi_jni_env"
100 params
.add
"java_class"
101 params
.add
"java_meth_id"
103 if mproperty
.is_init
then
104 jni_signature_alt
= mclass_type
.jni_signature_alt
105 return_type
= mclass_type
106 c_return_type
= mclass_type
.cname
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 c_return_type
= mclass_type
.cname
114 jni_signature_alt
= return_type
.jni_signature_alt
116 jni_signature_alt
= "Void"
122 for p
in signature
.mparameters
do params
.add
(p
.name
)
124 var cname
= "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
126 if return_type
!= null then
127 ccall
= "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
128 else ccall
= "{cname}({params.join(", ")});"
131 // execute implementation code
133 if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
134 PRINT_ERROR("Nit FFI with Java error: Exception after call.\\n");
135 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
139 (*nit_ffi_jni_env)->DeleteLocalRef(nit_ffi_jni_env, java_class);
142 if return_type
!= null then
143 fc
.exprs
.add
"\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
146 ccu
.add_exported_function
( fc
)
148 # Java implementation function in Java
149 var java_csig
= mproperty
.build_csignature
(mclass_type
, mmodule
, "___java_impl", long_signature
, java_call_context
)
150 mmodule
.java_file
.class_content
.add
"""
151 public static {{{java_csig}}} {
152 // from Nit FII at: {{{block.location}}}
158 redef fun compile_extern_class
(block
, m
, ccu
, mmodule
) do end
160 redef fun get_ftype
(block
, m
) do return new ForeignJavaType(block
.code
)
162 redef fun compile_to_files
(mmodule
, compdir
)
164 # Make sure we have a .java file
165 mmodule
.ensure_java_files
167 # Needed compiler and linker options
168 mmodule
.insert_compiler_options
170 # Enable linking C callbacks to java native methods
171 mmodule
.ensure_linking_callback_methods
(ffi_ccu
.as(not null), mmodule
.ffi_callbacks
[self])
173 # Java implementation code
174 var java_file
= mmodule
.java_file
175 assert java_file
!= null
176 var extern_java_file
= java_file
.write_to_files
(compdir
)
177 mmodule
.ffi_files
.add
(extern_java_file
)
180 var ffi_ccu
: nullable CCompilationUnit = null # HACK
182 redef fun compile_callback
(callback
, mmodule
, mainmodule
, ccu
)
185 callback
.compile_callback_to_java
(mmodule
, mainmodule
, ccu
)
191 # Pure java class source file
192 private var java_file
: nullable JavaClassTemplate = null
194 # Set up the templates of the Java implementation class
195 private fun ensure_java_files
197 if java_file
!= null then return
199 # Java implementation code
200 java_file
= new JavaClassTemplate(impl_java_class_name
)
203 # Compile C code to call JNI and link C callbacks implementations to Java extern methods
204 private fun ensure_linking_callback_methods
(ccu
: CCompilationUnit, callbacks
: Set[NitniCallback])
206 if callbacks
.is_empty
then
207 ccu
.body_decl
.add
"static int nit_ffi_with_java_registered_natives = 1;\n"
211 ccu
.body_decl
.add
"static int nit_ffi_with_java_registered_natives = 0;\n"
213 var jni_methods
= new Array[String]
214 for cb
in callbacks
do
215 jni_methods
.add_all
(cb
.jni_methods_declaration
(self))
218 var cf
= new CFunction("static void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
220 nit_ffi_with_java_registered_natives = 1;
222 jint n_methods = {{{jni_methods.length}}};
223 JNINativeMethod methods[] = {
224 {{{jni_methods.join(",\n\t\t")}}}
226 jint res = (*env)->RegisterNatives(env, jclazz, methods, n_methods);
228 PRINT_ERROR("RegisterNatives failed\\n");
229 (*env)->ExceptionDescribe(env);
233 ccu
.add_local_function cf
236 # Tell the C compiler where to find jni.h and how to link with libjvm
237 private fun insert_compiler_options
239 c_compiler_options
= "{c_compiler_options} -I $(JAVA_HOME)/include/"
240 c_linker_options
= "{c_linker_options} -L $(JNI_LIB_PATH) -ljvm"
243 # Name of the generated Java class where to store all implementation methods of this module
244 # as well as generated callbacks.
245 private fun impl_java_class_name
: String do return "Nit_{name}"
248 redef class AExternPropdef
249 redef fun verify_nitni_callbacks
(toolcontext
)
253 var block
= n_extern_code_block
254 if block
!= null and block
.is_java
then
255 insert_artificial_callbacks
(toolcontext
)
259 # Insert additionnal explicit calls to get the current `JNIEnv`
261 # This forces declaration of callbacks to Nit. The callbacks will be available in Java
262 # but will be used mainly by the FFI itself.
264 # The developper can aso customize the JNIEnv used by the FFI by redefing `Sys::jni_env`.
265 private fun insert_artificial_callbacks
(toolcontext
: ToolContext)
267 var fcc
= foreign_callbacks
270 var modelbuilder
= toolcontext
.modelbuilder
271 var mmodule
= mpropdef
.mclassdef
.mmodule
273 # We use callbacks from the C FFI since they will be called from generated C
274 var c_language_visitor
= toolcontext
.ffi_language_assignation_phase
.as(FFILanguageAssignationPhase).c_language
275 if not mmodule
.ffi_callbacks
.keys
.has
(c_language_visitor
) then
276 mmodule
.ffi_callbacks
[c_language_visitor
] = new HashSet[NitniCallback]
280 var pointer_class
= modelbuilder
.try_get_mclass_by_name
(self, mmodule
, "Pointer")
281 assert pointer_class
!= null
282 var pointer_sys_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, pointer_class
.mclass_type
, "sys")
283 assert pointer_sys_meth
!= null and pointer_sys_meth
isa MMethod
285 var explicit_call
= new MExplicitCall(pointer_class
.mclass_type
, pointer_sys_meth
, mmodule
)
286 fcc
.callbacks
.add
(explicit_call
)
287 mmodule
.ffi_callbacks
[c_language_visitor
].add
(explicit_call
)
290 var sys_class
= modelbuilder
.try_get_mclass_by_name
(self, mmodule
, "Sys")
291 assert sys_class
!= null
292 var sys_jni_env_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, sys_class
.mclass_type
, "jni_env")
293 if sys_jni_env_meth
== null or not sys_jni_env_meth
isa MMethod then
294 toolcontext
.error
(self.location
, "Java FFI error: you must import the `java` module when using the FFI with Java")
298 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_env_meth
, mmodule
)
299 fcc
.callbacks
.add
(explicit_call
)
300 mmodule
.ffi_callbacks
[c_language_visitor
].add
(explicit_call
)
303 var sys_jni_load_jclass_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, sys_class
.mclass_type
, "load_jclass")
304 assert sys_jni_load_jclass_meth
!= null
305 assert sys_jni_load_jclass_meth
isa MMethod
307 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_load_jclass_meth
, mmodule
)
308 fcc
.callbacks
.add
(explicit_call
)
309 mmodule
.ffi_callbacks
[c_language_visitor
].add
(explicit_call
)
310 explicit_call
.fill_type_for
(fcc
, mmodule
)
314 redef class AExternCodeBlock
315 fun is_java
: Bool do return language_name
!= null and
316 language_name_lowered
== "java"
319 # Java class source template
320 class JavaClassTemplate
323 var java_class_name
: String
324 init(name
: String) do self.java_class_name
= name
326 var header
= new Template
327 var class_content
= new Template
329 fun write_to_files
(compdir
: String): ExternFile
331 var filename
= "{java_class_name}.java"
332 var filepath
= "{compdir}/{filename}"
334 write_to_file filepath
336 return new JavaFile(filename
)
343 add
"public class {java_class_name} \{\n"
349 # A generated Java source file, represent the corresponding Makefile rules
353 redef fun makefile_rule_name
do return "{filename.basename(".java")}.class"
354 redef fun makefile_rule_content
do return "javac {filename.basename("")} -d ."
355 redef fun add_to_jar
do return true
358 # Context in pure Java code
359 private class JavaCallContext
362 redef fun name_mtype
(mtype
) do return mtype
.java_type
365 # Context in C, when call are from normal C to JNI
366 private class ToJavaCallContext
369 redef fun cast_to
(mtype
, name
) do return "({mtype.jni_type})({name})"
370 redef fun cast_from
(mtype
, name
) do return "({mtype.cname})({name})"
371 redef fun name_mtype
(mtype
) do return mtype
.jni_type
374 # Context in C, when call are from JNI to normal C
375 private class FromJavaCallContext
378 redef fun cast_to
(mtype
, name
) do return "({mtype.cname})({name})"
379 redef fun cast_from
(mtype
, name
) do return "({mtype.jni_type})({name})"
380 redef fun name_mtype
(mtype
) do return mtype
.jni_type
383 # Foreign type attach to Nit extern Java classes
384 class ForeignJavaType
387 var java_type
: String
388 init (java_type
: String) do self.java_type
= java_type
391 redef class NitniCallback
392 # Compile C and Java code to implement this callback
393 fun compile_callback_to_java
(mmodule
: MModule, mainmodule
: MModule, ccu
: CCompilationUnit) do end
395 # Returns the list of C functions to link with extern Java methods, as required
396 # to enable this callback from Java code.
398 # Return used by `MModule::ensure_linking_callback_methods`
400 # TODO we return an Array to support cast and other features like that
401 fun jni_methods_declaration
(from_module
: MModule): Array[String] do return new Array[String]
404 redef class MExplicitCall
405 redef fun compile_callback_to_java
(mmodule
, mainmodule
, ccu
)
407 var mproperty
= mproperty
408 assert mproperty
isa MMethod
410 # In C, indirection implementing the Java extern methods
411 var csignature
= mproperty
.build_c_implementation_signature
(recv_mtype
, mmodule
, "___indirect", long_signature
, from_java_call_context
)
412 var cf
= new CFunction("JNIEXPORT {csignature}")
413 cf
.exprs
.add
"\t{mproperty.build_ccall(recv_mtype, mainmodule, null, long_signature, from_java_call_context, null)}\n"
414 ccu
.add_local_function cf
416 # In Java, declare the extern method as a private static local method
417 var java_signature
= mproperty
.build_csignature
(recv_mtype
, mainmodule
, null, short_signature
, java_call_context
)
418 mmodule
.java_file
.class_content
.add
"private native static {java_signature};\n"
421 redef fun jni_methods_declaration
(from_mmodule
)
423 var mproperty
= mproperty
424 assert mproperty
isa MMethod
426 var java_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, null, short_signature
)
427 var jni_format
= mproperty
.build_jni_format
(recv_mtype
, from_mmodule
)
428 var c_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, "___indirect", long_signature
)
430 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
438 # * Primitives common to both languages use their Java primitive type
439 # * Nit extern Java classes are reprensented by their full Java type
440 # * Other Nit objects are represented by `int` in Java. It holds the
441 # pointer to the underlying C structure.
442 # TODO create static Java types to store and hide the pointer
443 private fun java_type
: String do return "int"
445 # JNI type name (in C)
447 # So this is a C type, usually defined in `jni.h`
448 private fun jni_type
: String do return "jint"
450 # JNI short type name (for signatures)
452 # Is used by `MMethod::build_jni_format` to pass a Java method signature
453 # to the JNI function `GetStaticMetodId`.
454 private fun jni_format
: String do return "I"
456 # Type name appearing within JNI function names.
458 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
459 # This strategy is used by JNI to type the return of callbacks to Java.
460 private fun jni_signature_alt
: String do return "Int"
463 redef class MClassType
466 var ftype
= mclass
.ftype
467 if ftype
isa ForeignJavaType then return ftype
.java_type
.
468 replace
('/', ".").replace
('$', ".").replace
(' ', "").replace
('\n',"")
469 if mclass
.name
== "Bool" then return "boolean"
470 if mclass
.name
== "Char" then return "char"
471 if mclass
.name
== "Int" then return "int"
472 if mclass
.name
== "Float" then return "double"
478 var ftype
= mclass
.ftype
479 if ftype
isa ForeignJavaType then return "jobject"
480 if mclass
.name
== "Bool" then return "jboolean"
481 if mclass
.name
== "Char" then return "jchar"
482 if mclass
.name
== "Int" then return "jint"
483 if mclass
.name
== "Float" then return "jdouble"
489 var ftype
= mclass
.ftype
490 if ftype
isa ForeignJavaType then
491 var ori_jni_type
= jni_type
492 var jni_type
= ftype
.java_type
.
493 replace
('.', "/").replace
(' ', "").replace
('\n', "")
495 # Remove parameters of generic types
497 var i
= jni_type
.last_index_of
('<')
499 var j
= jni_type
.index_of_from
('>', i
)
501 print
"Error: missing closing '>' in extern Java type of \"{mclass.name}\
""
504 jni_type
= jni_type
.substring
(0, i
) +
505 jni_type
.substring
(j
+1, jni_type
.length
)
509 return "L{jni_type};"
511 if mclass
.name
== "Bool" then return "Z"
512 if mclass
.name
== "Char" then return "C"
513 if mclass
.name
== "Int" then return "I"
514 if mclass
.name
== "Float" then return "D"
518 redef fun jni_signature_alt
520 var ftype
= mclass
.ftype
521 if ftype
isa ForeignJavaType then return "Object"
522 if mclass
.name
== "Bool" then return "Boolean"
523 if mclass
.name
== "Char" then return "Char"
524 if mclass
.name
== "Int" then return "Int"
525 if mclass
.name
== "Float" then return "Double"
531 # Returns the JNI signature format of this Nit method
533 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
534 # the JNI format `(ZIDLjava/lang/string;)V"
535 private fun build_jni_format
(recv_mtype
: MClassType, from_mmodule
: MModule): String
537 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
538 var msignature
= mmethoddef
.msignature
539 var format
= new Array[String]
544 if not self.is_init
then format
.add recv_mtype
.jni_format
547 for p
in msignature
.mparameters
do
548 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
549 format
.add param_mtype
.jni_format
555 format
.add recv_mtype
.jni_format
557 var return_mtype
= msignature
.return_mtype
558 if return_mtype
!= null then
559 return_mtype
= return_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
560 format
.add return_mtype
.jni_format
564 return format
.join
("")
567 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
568 # implementing Java extern methods.
570 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
571 private fun build_c_implementation_signature
(recv_mtype
: MClassType, from_mmodule
: MModule,
572 suffix
: nullable String, length
: SignatureLength, call_context
: CallContext): String
574 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
575 var signature
= mmethoddef
.msignature
576 assert signature
!= null
580 creturn_type
= call_context
.name_mtype
(recv_mtype
)
581 else if signature
.return_mtype
!= null then
582 var ret_mtype
= signature
.return_mtype
583 ret_mtype
= ret_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
584 creturn_type
= call_context
.name_mtype
(ret_mtype
)
586 creturn_type
= "void"
589 var cname
= build_cname
(recv_mtype
, from_mmodule
, suffix
, length
)
591 var cparams
= new List[String]
594 cparams
.add
"JNIEnv *env"
595 cparams
.add
"jclass clazz"
597 if not self.is_init
then
598 cparams
.add
"{call_context.name_mtype(recv_mtype)} recv"
600 for p
in signature
.mparameters
do
601 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
602 cparams
.add
"{call_context.name_mtype(param_mtype)} {p.name}"
605 return "{creturn_type} {cname}( {cparams.join(", ")} )"
609 private fun java_call_context
: JavaCallContext do return new JavaCallContext
610 private fun to_java_call_context
: ToJavaCallContext do return new ToJavaCallContext
611 private fun from_java_call_context
: FromJavaCallContext do return new FromJavaCallContext