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 assert sys_jni_env_meth
!= null
294 assert sys_jni_env_meth
isa MMethod
296 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_env_meth
, mmodule
)
297 fcc
.callbacks
.add
(explicit_call
)
298 mmodule
.ffi_callbacks
[c_language_visitor
].add
(explicit_call
)
301 var sys_jni_load_jclass_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, sys_class
.mclass_type
, "load_jclass")
302 assert sys_jni_load_jclass_meth
!= null
303 assert sys_jni_load_jclass_meth
isa MMethod
305 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_load_jclass_meth
, mmodule
)
306 fcc
.callbacks
.add
(explicit_call
)
307 mmodule
.ffi_callbacks
[c_language_visitor
].add
(explicit_call
)
308 explicit_call
.fill_type_for
(fcc
, mmodule
)
312 redef class AExternCodeBlock
313 fun is_java
: Bool do return language_name
!= null and
314 language_name_lowered
== "java"
317 # Java class source template
318 class JavaClassTemplate
321 var java_class_name
: String
322 init(name
: String) do self.java_class_name
= name
324 var header
= new Template
325 var class_content
= new Template
327 fun write_to_files
(compdir
: String): ExternFile
329 var filename
= "{java_class_name}.java"
330 var filepath
= "{compdir}/{filename}"
332 write_to_file filepath
334 return new JavaFile(filename
)
341 add
"public class {java_class_name} \{\n"
347 # A generated Java source file, represent the corresponding Makefile rules
351 redef fun makefile_rule_name
do return "{filename.basename(".java")}.class"
352 redef fun makefile_rule_content
do return "javac {filename} -d ."
353 redef fun add_to_jar
do return true
356 # Context in pure Java code
357 private class JavaCallContext
360 redef fun name_mtype
(mtype
) do return mtype
.java_type
363 # Context in C, when call are from normal C to JNI
364 private class ToJavaCallContext
367 redef fun cast_to
(mtype
, name
) do return "({mtype.jni_type})({name})"
368 redef fun cast_from
(mtype
, name
) do return "({mtype.cname})({name})"
369 redef fun name_mtype
(mtype
) do return mtype
.jni_type
372 # Context in C, when call are from JNI to normal C
373 private class FromJavaCallContext
376 redef fun cast_to
(mtype
, name
) do return "({mtype.cname})({name})"
377 redef fun cast_from
(mtype
, name
) do return "({mtype.jni_type})({name})"
378 redef fun name_mtype
(mtype
) do return mtype
.jni_type
381 # Foreign type attach to Nit extern Java classes
382 class ForeignJavaType
385 var java_type
: String
386 init (java_type
: String) do self.java_type
= java_type
389 redef class NitniCallback
390 # Compile C and Java code to implement this callback
391 fun compile_callback_to_java
(mmodule
: MModule, mainmodule
: MModule, ccu
: CCompilationUnit) do end
393 # Returns the list of C functions to link with extern Java methods, as required
394 # to enable this callback from Java code.
396 # Return used by `MModule::ensure_linking_callback_methods`
398 # TODO we return an Array to support cast and other features like that
399 fun jni_methods_declaration
(from_module
: MModule): Array[String] do return new Array[String]
402 redef class MExplicitCall
403 redef fun compile_callback_to_java
(mmodule
, mainmodule
, ccu
)
405 var mproperty
= mproperty
406 assert mproperty
isa MMethod
408 # In C, indirection implementing the Java extern methods
409 var csignature
= mproperty
.build_c_implementation_signature
(recv_mtype
, mmodule
, "___indirect", long_signature
, from_java_call_context
)
410 var cf
= new CFunction("JNIEXPORT {csignature}")
411 cf
.exprs
.add
"\t{mproperty.build_ccall(recv_mtype, mainmodule, null, long_signature, from_java_call_context, null)}\n"
412 ccu
.add_local_function cf
414 # In Java, declare the extern method as a private static local method
415 var java_signature
= mproperty
.build_csignature
(recv_mtype
, mainmodule
, null, short_signature
, java_call_context
)
416 mmodule
.java_file
.class_content
.add
"private native static {java_signature};\n"
419 redef fun jni_methods_declaration
(from_mmodule
)
421 var mproperty
= mproperty
422 assert mproperty
isa MMethod
424 var java_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, null, short_signature
)
425 var jni_format
= mproperty
.build_jni_format
(recv_mtype
, from_mmodule
)
426 var c_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, "___indirect", long_signature
)
428 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
436 # * Primitives common to both languages use their Java primitive type
437 # * Nit extern Java classes are reprensented by their full Java type
438 # * Other Nit objects are represented by `int` in Java. It holds the
439 # pointer to the underlying C structure.
440 # TODO create static Java types to store and hide the pointer
441 private fun java_type
: String do return "int"
443 # JNI type name (in C)
445 # So this is a C type, usually defined in `jni.h`
446 private fun jni_type
: String do return "jint"
448 # JNI short type name (for signatures)
450 # Is used by `MMethod::build_jni_format` to pass a Java method signature
451 # to the JNI function `GetStaticMetodId`.
452 private fun jni_format
: String do return "I"
454 # Type name appearing within JNI function names.
456 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
457 # This strategy is used by JNI to type the return of callbacks to Java.
458 private fun jni_signature_alt
: String do return "Int"
461 redef class MClassType
464 var ftype
= mclass
.ftype
465 if ftype
isa ForeignJavaType then return ftype
.java_type
.
466 replace
('/', ".").replace
('$', ".").replace
(' ', "")
467 if mclass
.name
== "Bool" then return "boolean"
468 if mclass
.name
== "Char" then return "char"
469 if mclass
.name
== "Int" then return "int"
470 if mclass
.name
== "Float" then return "double"
476 var ftype
= mclass
.ftype
477 if ftype
isa ForeignJavaType then return "jobject"
478 if mclass
.name
== "Bool" then return "jboolean"
479 if mclass
.name
== "Char" then return "jchar"
480 if mclass
.name
== "Int" then return "jint"
481 if mclass
.name
== "Float" then return "jdouble"
487 var ftype
= mclass
.ftype
488 if ftype
isa ForeignJavaType then return "L{ftype.java_type.replace('.', "/").replace(' ', "")};"
489 if mclass
.name
== "Bool" then return "Z"
490 if mclass
.name
== "Char" then return "C"
491 if mclass
.name
== "Int" then return "I"
492 if mclass
.name
== "Float" then return "D"
496 redef fun jni_signature_alt
498 var ftype
= mclass
.ftype
499 if ftype
isa ForeignJavaType then return "Object"
500 if mclass
.name
== "Bool" then return "Boolean"
501 if mclass
.name
== "Char" then return "Char"
502 if mclass
.name
== "Int" then return "Int"
503 if mclass
.name
== "Float" then return "Double"
509 # Returns the JNI signature format of this Nit method
511 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
512 # the JNI format `(ZIDLjava/lang/string;)V"
513 private fun build_jni_format
(recv_mtype
: MClassType, from_mmodule
: MModule): String
515 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
516 var msignature
= mmethoddef
.msignature
517 var format
= new Array[String]
522 if not self.is_init
then format
.add recv_mtype
.jni_format
525 for p
in msignature
.mparameters
do
526 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
527 format
.add param_mtype
.jni_format
533 format
.add recv_mtype
.jni_format
535 var return_mtype
= msignature
.return_mtype
536 if return_mtype
!= null then
537 return_mtype
= return_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
538 format
.add return_mtype
.jni_format
542 return format
.join
("")
545 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
546 # implementing Java extern methods.
548 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
549 private fun build_c_implementation_signature
(recv_mtype
: MClassType, from_mmodule
: MModule,
550 suffix
: nullable String, length
: SignatureLength, call_context
: CallContext): String
552 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
553 var signature
= mmethoddef
.msignature
554 assert signature
!= null
558 creturn_type
= call_context
.name_mtype
(recv_mtype
)
559 else if signature
.return_mtype
!= null then
560 var ret_mtype
= signature
.return_mtype
561 ret_mtype
= ret_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
562 creturn_type
= call_context
.name_mtype
(ret_mtype
)
564 creturn_type
= "void"
567 var cname
= build_cname
(recv_mtype
, from_mmodule
, suffix
, length
)
569 var cparams
= new List[String]
572 cparams
.add
"JNIEnv *env"
573 cparams
.add
"jclass clazz"
575 if not self.is_init
then
576 cparams
.add
"{call_context.name_mtype(recv_mtype)} recv"
578 for p
in signature
.mparameters
do
579 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
580 cparams
.add
"{call_context.name_mtype(param_mtype)} {p.name}"
583 return "{creturn_type} {cname}( {cparams.join(", ")} )"
587 private fun java_call_context
: JavaCallContext do return new JavaCallContext
588 private fun to_java_call_context
: ToJavaCallContext do return new ToJavaCallContext
589 private fun from_java_call_context
: FromJavaCallContext do return new FromJavaCallContext