nitg: use a portable macro PRINT_ERROR instead of fprintf
[nit.git] / src / common_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, nmodule)
36 do
37 nmodule.ensure_java_files
38 var java_file = nmodule.java_file
39 assert java_file != null
40
41 java_file.header.add(block.code)
42 end
43
44 redef fun compile_extern_method(block, m, ccu, nmodule)
45 do
46 ffi_ccu = ccu
47 nmodule.ensure_java_files
48 var java_file = nmodule.java_file
49 assert java_file != null
50
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
55
56 # C function calling the Java method through JNI
57 var fc = new ExternCFunction(m, mmodule)
58
59 fc.exprs.add """
60 jclass java_class;
61 jmethodID java_meth_id;
62
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);
66
67 // retrieve the implementation Java class
68 java_class = (*nit_ffi_jni_env)->FindClass(nit_ffi_jni_env, "{{{mmodule.impl_java_class_name}}}");
69 if (java_class == NULL) {
70 PRINT_ERROR("Nit FFI with Java error: failed to load class.\\n");
71 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
72 exit(1);
73 }
74
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);
77 """
78
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)
82 fc.exprs.add """
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 PRINT_ERROR("Nit FFI with Java error: Java implementation not found.\\n");
87 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
88 exit(1);
89 }
90 """
91
92 # Call the C Java implementation method from C
93 var signature = mmethodef.msignature
94 assert signature != null
95
96 var jni_signature_alt
97 var return_type
98 var c_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 c_return_type = mclass_type.cname
108 else
109 params.add "recv"
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
116 else
117 jni_signature_alt = "Void"
118 return_type = null
119 c_return_type = null
120 end
121 end
122
123 for p in signature.mparameters do params.add(p.name)
124
125 var cname = "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
126 var ccall
127 if return_type != null then
128 ccall = "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
129 else ccall = "{cname}({params.join(", ")});"
130
131 fc.exprs.add """
132 // execute implementation code
133 {{{ccall}}}
134 if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
135 PRINT_ERROR("Nit FFI with Java error: Exception after call.\\n");
136 (*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
137 exit(1);
138 }
139 """
140
141 if return_type != null then
142 fc.exprs.add "\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
143 end
144
145 ccu.add_exported_function( fc )
146
147 # Java implementation function in Java
148 var java_csig = mproperty.build_csignature(mclass_type, mmodule, "___java_impl", long_signature, java_call_context)
149 nmodule.java_file.class_content.add """
150 public static {{{java_csig}}} {
151 // from Nit FII at: {{{block.location}}}
152 {{{block.code}}}
153 }
154 """
155 end
156
157 redef fun compile_extern_class(block, m, ccu, nmodule) do end
158
159 redef fun get_ftype(block, m) do return new ForeignJavaType(block.code)
160
161 redef fun compile_to_files(nmodule, compdir)
162 do
163 # Make sure we have a .java file
164 nmodule.ensure_java_files
165
166 # Needed compiler and linker options
167 nmodule.insert_compiler_options
168
169 # Enable linking C callbacks to java native methods
170 nmodule.ensure_linking_callback_methods(ffi_ccu, self.callbacks)
171
172 # Java implementation code
173 var java_file = nmodule.java_file
174 assert java_file != null
175 var extern_java_file = java_file.write_to_files(compdir)
176 nmodule.ffi_files.add(extern_java_file)
177 end
178
179 var callbacks = new HashSet[NitniCallback] # HACK
180 var ffi_ccu: CCompilationUnit # HACK
181
182 redef fun compile_callback(callback, nmodule, mainmodule, ccu)
183 do
184 ffi_ccu = ccu
185 callbacks.add callback
186 callback.compile_callback_to_java(nmodule, ccu)
187 end
188 end
189
190 redef class AModule
191
192 # Pure java class source file
193 private var java_file: nullable JavaClassTemplate = null
194
195 # Set up the templates of the Java implementation class
196 private fun ensure_java_files
197 do
198 if java_file != null then return
199
200 # Java implementation code
201 java_file = new JavaClassTemplate(mmodule.impl_java_class_name)
202 end
203
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])
206 do
207 if callbacks.is_empty then
208 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 1;\n"
209 return
210 end
211
212 ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 0;\n"
213
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)))
217 end
218
219 var cf = new CFunction("static void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
220 cf.exprs.add """
221 nit_ffi_with_java_registered_natives = 1;
222
223 jint n_methods = {{{jni_methods.length}}};
224 JNINativeMethod methods[] = {
225 {{{jni_methods.join(",\n\t\t")}}}
226 };
227 jint res = (*env)->RegisterNatives(env, jclazz, methods, n_methods);
228 if (res != JNI_OK) {
229 PRINT_ERROR("RegisterNatives failed\\n");
230 (*env)->ExceptionDescribe(env);
231 exit(1);
232 }
233 """
234 ccu.add_local_function cf
235 end
236
237 # Tell the C compiler where to find jni.h and how to link with libjvm
238 private fun insert_compiler_options
239 do
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"
242 end
243 end
244
245 redef class MModule
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 "NitFFIWithJava_{name}"
249 end
250
251 redef class AExternPropdef
252 redef fun verify_nitni_callbacks(toolcontext)
253 do
254 super
255
256 var block = n_extern_code_block
257 if block != null and block.is_java then
258 insert_articifial_callbacks(toolcontext)
259 end
260 end
261
262 # Insert additionnal explicit calls to get the current `JNIEnv`
263 #
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.
266 #
267 # The developper can aso customize the JNIEnv used by the FFI by redefing `Sys::jni_env`.
268 private fun insert_articifial_callbacks(toolcontext: ToolContext)
269 do
270 var fcc = foreign_callbacks
271 assert fcc != null
272
273 var modelbuilder = toolcontext.modelbuilder
274 var mmodule = mpropdef.mclassdef.mmodule
275
276 # Pointer::sys
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
281
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)
285
286 # Sys::jni_env
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
292
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)
296 end
297 end
298
299 redef class AExternCodeBlock
300 fun is_java : Bool do return language_name != null and
301 language_name_lowered == "java"
302 end
303
304 # Java class source template
305 class JavaClassTemplate
306 super Template
307
308 var java_class_name: String
309 init(name: String) do self.java_class_name = name
310
311 var header = new Template
312 var class_content = new Template
313
314 fun write_to_files(compdir: String): ExternFile
315 do
316 var filename = "{java_class_name}.java"
317 var filepath = "{compdir}/{filename}"
318
319 write_to_file filepath
320
321 return new JavaFile(filename)
322 end
323
324 redef fun rendering
325 do
326 add header
327 add "\n"
328 add "public class {java_class_name} \{\n"
329 add class_content
330 add "\}"
331 end
332 end
333
334 # A generated Java source file, represent the corresponding Makefile rules
335 class JavaFile
336 super ExternFile
337
338 redef fun makefile_rule_name do return "{filename.basename(".java")}.class"
339 redef fun makefile_rule_content do return "javac {filename} -d ."
340 redef fun add_to_jar do return true
341 end
342
343 # Context in pure Java code
344 private class JavaCallContext
345 super CallContext
346
347 redef fun name_mtype(mtype) do return mtype.java_type
348 end
349
350 # Context in C, when call are from normal C to JNI
351 private class ToJavaCallContext
352 super CallContext
353
354 redef fun cast_to(mtype, name) do return "({mtype.jni_type})({name})"
355 redef fun cast_from(mtype, name) do return "({mtype.cname})({name})"
356 redef fun name_mtype(mtype) do return mtype.jni_type
357 end
358
359 # Context in C, when call are from JNI to normal C
360 private class FromJavaCallContext
361 super CallContext
362
363 redef fun cast_to(mtype, name) do return "({mtype.cname})({name})"
364 redef fun cast_from(mtype, name) do return "({mtype.jni_type})({name})"
365 redef fun name_mtype(mtype) do return mtype.jni_type
366 end
367
368 # Foreign type attach to Nit extern Java classes
369 class ForeignJavaType
370 super ForeignType
371
372 var java_type: String
373 init (java_type: String) do self.java_type = java_type
374 end
375
376 redef class NitniCallback
377 # Compile C and Java code to implement this callback
378 fun compile_callback_to_java(nmodule: AModule, ccu: CCompilationUnit) do end
379
380 # Returns the list of C functions to link with extern Java methods, as required
381 # to enable this callback from Java code.
382 #
383 # Return used by `AModule::ensure_linking_callback_methods`
384 #
385 # TODO we return an Array to support cast and other features like that
386 fun jni_methods_declaration(from_module: MModule): Array[String] do return new Array[String]
387 end
388
389 redef class MExplicitCall
390 redef fun compile_callback_to_java(nmodule, ccu)
391 do
392 var mproperty = mproperty
393 assert mproperty isa MMethod
394 var mmodule = nmodule.mmodule.as(not null)
395
396 # In C, indirection implementing the Java extern methods
397 var csignature = mproperty.build_c_implementation_signature(recv_mtype, mmodule, "___indirect", long_signature, from_java_call_context)
398 var cf = new CFunction("JNIEXPORT {csignature}")
399 cf.exprs.add "\t{mproperty.build_ccall(recv_mtype, mmodule, null, long_signature, from_java_call_context, null)}\n"
400 ccu.add_local_function cf
401
402 # In Java, declare the extern method as a private static local method
403 var java_signature = mproperty.build_csignature(recv_mtype, mmodule, null, short_signature, java_call_context)
404 nmodule.java_file.class_content.add "private native static {java_signature};\n"
405 end
406
407 redef fun jni_methods_declaration(from_mmodule)
408 do
409 var mproperty = mproperty
410 assert mproperty isa MMethod
411
412 var java_name = mproperty.build_cname(recv_mtype, from_mmodule, null, short_signature)
413 var jni_format = mproperty.build_jni_format(recv_mtype, from_mmodule)
414 var c_name = mproperty.build_cname(recv_mtype, from_mmodule, "___indirect", long_signature)
415
416 return ["""{"{{{java_name}}}", "{{{jni_format}}}", {{{c_name}}}}"""]
417 end
418 end
419
420 redef class MType
421
422 # Type name in Java
423 #
424 # * Primitives common to both languages use their Java primitive type
425 # * Nit extern Java classes are reprensented by their full Java type
426 # * Other Nit objects are represented by `long` in Java. It holds the
427 # pointer to the underlying C structure.
428 # TODO create static Java types to store and hide the pointer
429 private fun java_type: String do return "long"
430
431 # JNI type name (in C)
432 #
433 # So this is a C type, usually defined in `jni.h`
434 private fun jni_type: String do return "jlong"
435
436 # JNI short type name (for signatures)
437 #
438 # Is used by `MMethod::build_jni_format` to pass a Java method signature
439 # to the JNI function `GetStaticMetodId`.
440 private fun jni_format: String do return "J"
441
442 # Type name appearing within JNI function names.
443 #
444 # Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
445 # This strategy is used by JNI to type the return of callbacks to Java.
446 private fun jni_signature_alt: String do return "Long"
447 end
448
449 redef class MClassType
450 redef fun java_type
451 do
452 var ftype = mclass.ftype
453 if ftype isa ForeignJavaType then return ftype.java_type
454 if mclass.name == "Bool" then return "boolean"
455 if mclass.name == "Char" then return "char"
456 if mclass.name == "Int" then return "int"
457 if mclass.name == "Float" then return "double"
458 return super
459 end
460
461 redef fun jni_type
462 do
463 var ftype = mclass.ftype
464 if ftype isa ForeignJavaType then return "jobject"
465 if mclass.name == "Bool" then return "jboolean"
466 if mclass.name == "Char" then return "jchar"
467 if mclass.name == "Int" then return "jint"
468 if mclass.name == "Float" then return "jdouble"
469 return super
470 end
471
472 redef fun jni_format
473 do
474 var ftype = mclass.ftype
475 if ftype isa ForeignJavaType then return "L{ftype.java_type.replace('.', "/").replace(' ', "")};"
476 if mclass.name == "Bool" then return "Z"
477 if mclass.name == "Char" then return "C"
478 if mclass.name == "Int" then return "I"
479 if mclass.name == "Float" then return "D"
480 return super
481 end
482
483 redef fun jni_signature_alt
484 do
485 var ftype = mclass.ftype
486 if ftype isa ForeignJavaType then return "Object"
487 if mclass.name == "Bool" then return "Bool"
488 if mclass.name == "Char" then return "Char"
489 if mclass.name == "Int" then return "Int"
490 if mclass.name == "Float" then return "Double"
491 return super
492 end
493 end
494
495 redef class MMethod
496 # Returns the JNI signature format of this Nit method
497 #
498 # Example: a Nity signature `(Bool, Int, Float, JavaString)` is represented by
499 # the JNI format `(ZIDLjava/lang/string;)V"
500 private fun build_jni_format(recv_mtype: MClassType, from_mmodule: MModule): String
501 do
502 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
503 var msignature = mmethoddef.msignature
504 var format = new Array[String]
505
506 format.add "("
507
508 # receiver
509 if not self.is_init then format.add recv_mtype.jni_format
510
511 # parameters
512 for p in msignature.mparameters do
513 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
514 format.add param_mtype.jni_format
515 end
516 format.add ")"
517
518 # return
519 if self.is_init then
520 format.add recv_mtype.jni_format
521 else
522 var return_mtype = msignature.return_mtype
523 if return_mtype != null then
524 format.add return_mtype.jni_format
525 else format.add "V"
526 end
527
528 return format.join("")
529 end
530
531 # Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
532 # implementing Java extern methods.
533 #
534 # Is used to generate FFI callbacks to Nit at `MExplicitCall::compile_callback_to_java`.
535 private fun build_c_implementation_signature(recv_mtype: MClassType, from_mmodule: MModule,
536 suffix: nullable String, length: SignatureLength, call_context: CallContext): String
537 do
538 var mmethoddef = lookup_first_definition(from_mmodule, recv_mtype)
539 var signature = mmethoddef.msignature
540 assert signature != null
541
542 var creturn_type
543 if self.is_init then
544 creturn_type = call_context.name_mtype(recv_mtype)
545 else if signature.return_mtype != null then
546 var ret_mtype = signature.return_mtype
547 ret_mtype = ret_mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
548 creturn_type = call_context.name_mtype(ret_mtype)
549 else
550 creturn_type = "void"
551 end
552
553 var cname = build_cname(recv_mtype, from_mmodule, suffix, length)
554
555 var cparams = new List[String]
556
557 # This is different
558 cparams.add "JNIEnv *env"
559 cparams.add "jclass clazz"
560
561 if not self.is_init then
562 cparams.add "{call_context.name_mtype(recv_mtype)} recv"
563 end
564 for p in signature.mparameters do
565 var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
566 cparams.add "{call_context.name_mtype(param_mtype)} {p.name}"
567 end
568
569 return "{creturn_type} {cname}( {cparams.join(", ")} )"
570 end
571 end
572
573 private fun java_call_context: JavaCallContext do return new JavaCallContext
574 private fun to_java_call_context: ToJavaCallContext do return new ToJavaCallContext
575 private fun from_java_call_context: FromJavaCallContext do return new FromJavaCallContext