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