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
, nmodule
)
37 nmodule
.ensure_java_files
38 var java_file
= nmodule
.java_file
39 assert java_file
!= null
41 java_file
.header
.add
(block
.code
)
44 redef fun compile_extern_method
(block
, m
, ccu
, nmodule
)
47 nmodule
.ensure_java_files
48 var java_file
= nmodule
.java_file
49 assert java_file
!= null
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
56 # C function calling the Java method through JNI
57 var fc
= new ExternCFunction(m
, mmodule
)
61 jmethodID java_meth_id;
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);
67 // retrieve the implementation Java class
68 java_class = {{{mmodule.name}}}___Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
69 if (java_class == NULL) {
70 fprintf(stderr, "Nit FFI with Java error: failed to load class.\\n");
71 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
75 // register callbacks (only once per Nit module)
76 if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
79 # Retrieve the Java implementation function id
80 var java_fun_name
= mproperty
.build_cname
(mclass_type
, mmodule
, "___java_impl", long_signature
)
81 var jni_format
= mproperty
.build_jni_format
(mclass_type
, mmodule
)
83 // retreive the implementation static function
84 java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
85 if (java_meth_id == NULL) {
86 fprintf(stderr, "Nit FFI with Java error: Java implementation not found.\\n");
87 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
92 # Call the C Java implementation method from C
93 var signature
= mmethodef
.msignature
94 assert signature
!= null
99 var params
= new Array[String]
100 params
.add
"nit_ffi_jni_env"
101 params
.add
"java_class"
102 params
.add
"java_meth_id"
104 if mproperty
.is_init
then
105 jni_signature_alt
= mclass_type
.jni_signature_alt
106 return_type
= mclass_type
107 c_return_type
= mclass_type
.cname
110 if signature
.return_mtype
!= null then
111 var ret_mtype
= signature
.return_mtype
112 ret_mtype
= ret_mtype
.resolve_for
(mclass_type
, mclass_type
, mmodule
, true)
113 return_type
= signature
.return_mtype
114 c_return_type
= mclass_type
.cname
115 jni_signature_alt
= return_type
.jni_signature_alt
117 jni_signature_alt
= "Void"
123 for p
in signature
.mparameters
do params
.add
(p
.name
)
125 var cname
= "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
127 if return_type
!= null then
128 ccall
= "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
129 else ccall
= "{cname}({params.join(", ")});"
132 // execute implementation code
134 if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
135 fprintf(stderr, "Nit FFI with Java error: Exception after call.\\n");
136 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
140 (*nit_ffi_jni_env)->DeleteLocalRef(nit_ffi_jni_env, java_class);
143 if return_type
!= null then
144 fc
.exprs
.add
"\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
147 ccu
.add_exported_function
( fc
)
149 # Java implementation function in Java
150 var java_csig
= mproperty
.build_csignature
(mclass_type
, mmodule
, "___java_impl", long_signature
, java_call_context
)
151 nmodule
.java_file
.class_content
.add
"""
152 public static {{{java_csig}}} {
153 // from Nit FII at: {{{block.location}}}
159 redef fun compile_extern_class
(block
, m
, ccu
, nmodule
) do end
161 redef fun get_ftype
(block
, m
) do return new ForeignJavaType(block
.code
)
163 redef fun compile_to_files
(nmodule
, compdir
)
165 # Make sure we have a .java file
166 nmodule
.ensure_java_files
168 # Needed compiler and linker options
169 nmodule
.insert_compiler_options
171 # Enable linking C callbacks to java native methods
172 nmodule
.ensure_linking_callback_methods
(ffi_ccu
.as(not null), nmodule
.ffi_callbacks
[self])
174 # Java implementation code
175 var java_file
= nmodule
.java_file
176 assert java_file
!= null
177 var extern_java_file
= java_file
.write_to_files
(compdir
)
178 nmodule
.ffi_files
.add
(extern_java_file
)
181 var ffi_ccu
: nullable CCompilationUnit = null # HACK
183 redef fun compile_callback
(callback
, nmodule
, mainmodule
, ccu
)
186 callback
.compile_callback_to_java
(nmodule
, ccu
)
192 # Pure java class source file
193 private var java_file
: nullable JavaClassTemplate = null
195 # Set up the templates of the Java implementation class
196 private fun ensure_java_files
198 if java_file
!= null then return
200 # Java implementation code
201 java_file
= new JavaClassTemplate(mmodule
.impl_java_class_name
)
204 # Compile C code to call JNI and link C callbacks implementations to Java extern methods
205 private fun ensure_linking_callback_methods
(ccu
: CCompilationUnit, callbacks
: Set[NitniCallback])
207 if callbacks
.is_empty
then
208 ccu
.body_decl
.add
"static int nit_ffi_with_java_registered_natives = 1;\n"
212 ccu
.body_decl
.add
"static int nit_ffi_with_java_registered_natives = 0;\n"
214 var jni_methods
= new Array[String]
215 for cb
in callbacks
do
216 jni_methods
.add_all
(cb
.jni_methods_declaration
(mmodule
.as(not null)))
219 var cf
= new CFunction("static void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
221 nit_ffi_with_java_registered_natives = 1;
223 jint n_methods = {{{jni_methods.length}}};
224 JNINativeMethod methods[] = {
225 {{{jni_methods.join(",\n\t\t")}}}
227 jint res = (*env)->RegisterNatives(env, jclazz, methods, n_methods);
229 fprintf(stderr, "RegisterNatives failed\\n");
230 (*env)->ExceptionDescribe(env);
234 ccu
.add_local_function cf
237 # Tell the C compiler where to find jni.h and how to link with libjvm
238 private fun insert_compiler_options
240 mmodule
.c_compiler_options
= "{mmodule.c_compiler_options} -I $(JAVA_HOME)/include/"
241 mmodule
.c_linker_options
= "{mmodule.c_linker_options} -L $(JNI_LIB_PATH) -ljvm"
246 # Name of the generated Java class where to store all implementation methods of this module
247 # as well as generated callbacks.
248 private fun impl_java_class_name
: String do return "Nit_{name}"
251 redef class AExternPropdef
252 redef fun verify_nitni_callbacks
(toolcontext
)
256 var block
= n_extern_code_block
257 if block
!= null and block
.is_java
then
258 insert_artificial_callbacks
(toolcontext
)
262 # Insert additionnal explicit calls to get the current `JNIEnv`
264 # This forces declaration of callbacks to Nit. The callbacks will be available in Java
265 # but will be used mainly by the FFI itself.
267 # The developper can aso customize the JNIEnv used by the FFI by redefing `Sys::jni_env`.
268 private fun insert_artificial_callbacks
(toolcontext
: ToolContext)
270 var fcc
= foreign_callbacks
273 var modelbuilder
= toolcontext
.modelbuilder
274 var mmodule
= mpropdef
.mclassdef
.mmodule
277 var pointer_class
= modelbuilder
.try_get_mclass_by_name
(self, mmodule
, "Pointer")
278 assert pointer_class
!= null
279 var pointer_sys_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, pointer_class
.mclass_type
, "sys")
280 assert pointer_sys_meth
!= null and pointer_sys_meth
isa MMethod
282 var explicit_call
= new MExplicitCall(pointer_class
.mclass_type
, pointer_sys_meth
, mmodule
)
283 fcc
.callbacks
.add
(explicit_call
)
284 explicit_call
.fill_type_for
(fcc
, mmodule
)
287 var sys_class
= modelbuilder
.try_get_mclass_by_name
(self, mmodule
, "Sys")
288 assert sys_class
!= null
289 var sys_jni_env_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, sys_class
.mclass_type
, "jni_env")
290 assert sys_jni_env_meth
!= null
291 assert sys_jni_env_meth
isa MMethod
293 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_env_meth
, mmodule
)
294 fcc
.callbacks
.add
(explicit_call
)
295 explicit_call
.fill_type_for
(fcc
, mmodule
)
298 var sys_jni_load_jclass_meth
= modelbuilder
.try_get_mproperty_by_name2
(self, mmodule
, sys_class
.mclass_type
, "load_jclass")
299 assert sys_jni_load_jclass_meth
!= null
300 assert sys_jni_load_jclass_meth
isa MMethod
302 explicit_call
= new MExplicitCall(sys_class
.mclass_type
, sys_jni_load_jclass_meth
, mmodule
)
303 fcc
.callbacks
.add
(explicit_call
)
304 explicit_call
.fill_type_for
(fcc
, mmodule
)
308 redef class AExternCodeBlock
309 fun is_java
: Bool do return language_name
!= null and
310 language_name_lowered
== "java"
313 # Java class source template
314 class JavaClassTemplate
317 var java_class_name
: String
318 init(name
: String) do self.java_class_name
= name
320 var header
= new Template
321 var class_content
= new Template
323 fun write_to_files
(compdir
: String): ExternFile
325 var filename
= "{java_class_name}.java"
326 var filepath
= "{compdir}/{filename}"
328 write_to_file filepath
330 return new JavaFile(filename
)
337 add
"public class {java_class_name} \{\n"
343 # A generated Java source file, represent the corresponding Makefile rules
347 redef fun makefile_rule_name
do return "{filename.basename(".java")}.class"
348 redef fun makefile_rule_content
do return "javac {filename} -d ."
349 redef fun add_to_jar
do return true
352 # Context in pure Java code
353 private class JavaCallContext
356 redef fun name_mtype
(mtype
) do return mtype
.java_type
359 # Context in C, when call are from normal C to JNI
360 private class ToJavaCallContext
363 redef fun cast_to
(mtype
, name
) do return "({mtype.jni_type})({name})"
364 redef fun cast_from
(mtype
, name
) do return "({mtype.cname})({name})"
365 redef fun name_mtype
(mtype
) do return mtype
.jni_type
368 # Context in C, when call are from JNI to normal C
369 private class FromJavaCallContext
372 redef fun cast_to
(mtype
, name
) do return "({mtype.cname})({name})"
373 redef fun cast_from
(mtype
, name
) do return "({mtype.jni_type})({name})"
374 redef fun name_mtype
(mtype
) do return mtype
.jni_type
377 # Foreign type attach to Nit extern Java classes
378 class ForeignJavaType
381 var java_type
: String
382 init (java_type
: String) do self.java_type
= java_type
385 redef class NitniCallback
386 # Compile C and Java code to implement this callback
387 fun compile_callback_to_java
(nmodule
: AModule, ccu
: CCompilationUnit) do end
389 # Returns the list of C functions to link with extern Java methods, as required
390 # to enable this callback from Java code.
392 # Return used by `AModule::ensure_linking_callback_methods`
394 # TODO we return an Array to support cast and other features like that
395 fun jni_methods_declaration
(from_module
: MModule): Array[String] do return new Array[String]
398 redef class MExplicitCall
399 redef fun compile_callback_to_java
(nmodule
, ccu
)
401 var mproperty
= mproperty
402 assert mproperty
isa MMethod
403 var mmodule
= nmodule
.mmodule
.as(not null)
405 # In C, indirection implementing the Java extern methods
406 var csignature
= mproperty
.build_c_implementation_signature
(recv_mtype
, mmodule
, "___indirect", long_signature
, from_java_call_context
)
407 var cf
= new CFunction("JNIEXPORT {csignature}")
408 cf
.exprs
.add
"\t{mproperty.build_ccall(recv_mtype, mmodule, null, long_signature, from_java_call_context, null)}\n"
409 ccu
.add_local_function cf
411 # In Java, declare the extern method as a private static local method
412 var java_signature
= mproperty
.build_csignature
(recv_mtype
, mmodule
, null, short_signature
, java_call_context
)
413 nmodule
.java_file
.class_content
.add
"private native static {java_signature};\n"
416 redef fun jni_methods_declaration
(from_mmodule
)
418 var mproperty
= mproperty
419 assert mproperty
isa MMethod
421 var java_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, null, short_signature
)
422 var jni_format
= mproperty
.build_jni_format
(recv_mtype
, from_mmodule
)
423 var c_name
= mproperty
.build_cname
(recv_mtype
, from_mmodule
, "___indirect", long_signature
)
425 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
433 # * Primitives common to both languages use their Java primitive type
434 # * Nit extern Java classes are reprensented by their full Java type
435 # * Other Nit objects are represented by `int` in Java. It holds the
436 # pointer to the underlying C structure.
437 # TODO create static Java types to store and hide the pointer
438 private fun java_type
: String do return "int"
440 # JNI type name (in C)
442 # So this is a C type, usually defined in `jni.h`
443 private fun jni_type
: String do return "jint"
445 # JNI short type name (for signatures)
447 # Is used by `MMethod::build_jni_format` to pass a Java method signature
448 # to the JNI function `GetStaticMetodId`.
449 private fun jni_format
: String do return "I"
451 # Type name appearing within JNI function names.
453 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
454 # This strategy is used by JNI to type the return of callbacks to Java.
455 private fun jni_signature_alt
: String do return "Int"
458 redef class MClassType
461 var ftype
= mclass
.ftype
462 if ftype
isa ForeignJavaType then return ftype
.java_type
463 if mclass
.name
== "Bool" then return "boolean"
464 if mclass
.name
== "Char" then return "char"
465 if mclass
.name
== "Int" then return "int"
466 if mclass
.name
== "Float" then return "double"
472 var ftype
= mclass
.ftype
473 if ftype
isa ForeignJavaType then return "jobject"
474 if mclass
.name
== "Bool" then return "jboolean"
475 if mclass
.name
== "Char" then return "jchar"
476 if mclass
.name
== "Int" then return "jint"
477 if mclass
.name
== "Float" then return "jdouble"
483 var ftype
= mclass
.ftype
484 if ftype
isa ForeignJavaType then return "L{ftype.java_type.replace('.', "/").replace(' ', "")};"
485 if mclass
.name
== "Bool" then return "Z"
486 if mclass
.name
== "Char" then return "C"
487 if mclass
.name
== "Int" then return "I"
488 if mclass
.name
== "Float" then return "D"
492 redef fun jni_signature_alt
494 var ftype
= mclass
.ftype
495 if ftype
isa ForeignJavaType then return "Object"
496 if mclass
.name
== "Bool" then return "Boolean"
497 if mclass
.name
== "Char" then return "Char"
498 if mclass
.name
== "Int" then return "Int"
499 if mclass
.name
== "Float" then return "Double"
505 # Returns the JNI signature format of this Nit method
507 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
508 # the JNI format `(ZIDLjava/lang/string;)V"
509 private fun build_jni_format
(recv_mtype
: MClassType, from_mmodule
: MModule): String
511 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
512 var msignature
= mmethoddef
.msignature
513 var format
= new Array[String]
518 if not self.is_init
then format
.add recv_mtype
.jni_format
521 for p
in msignature
.mparameters
do
522 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
523 format
.add param_mtype
.jni_format
529 format
.add recv_mtype
.jni_format
531 var return_mtype
= msignature
.return_mtype
532 if return_mtype
!= null then
533 return_mtype
= return_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
534 format
.add return_mtype
.jni_format
538 return format
.join
("")
541 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
542 # implementing Java extern methods.
544 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
545 private fun build_c_implementation_signature
(recv_mtype
: MClassType, from_mmodule
: MModule,
546 suffix
: nullable String, length
: SignatureLength, call_context
: CallContext): String
548 var mmethoddef
= lookup_first_definition
(from_mmodule
, recv_mtype
)
549 var signature
= mmethoddef
.msignature
550 assert signature
!= null
554 creturn_type
= call_context
.name_mtype
(recv_mtype
)
555 else if signature
.return_mtype
!= null then
556 var ret_mtype
= signature
.return_mtype
557 ret_mtype
= ret_mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
558 creturn_type
= call_context
.name_mtype
(ret_mtype
)
560 creturn_type
= "void"
563 var cname
= build_cname
(recv_mtype
, from_mmodule
, suffix
, length
)
565 var cparams
= new List[String]
568 cparams
.add
"JNIEnv *env"
569 cparams
.add
"jclass clazz"
571 if not self.is_init
then
572 cparams
.add
"{call_context.name_mtype(recv_mtype)} recv"
574 for p
in signature
.mparameters
do
575 var param_mtype
= p
.mtype
.resolve_for
(recv_mtype
, recv_mtype
, from_mmodule
, true)
576 cparams
.add
"{call_context.name_mtype(param_mtype)} {p.name}"
579 return "{creturn_type} {cname}( {cparams.join(", ")} )"
583 private fun java_call_context
: JavaCallContext do return new JavaCallContext
584 private fun to_java_call_context
: ToJavaCallContext do return new ToJavaCallContext
585 private fun from_java_call_context
: FromJavaCallContext do return new FromJavaCallContext