<commit_before># This file is part of NIT ( http://www.nitlanguage.org ).
#
# Copyright 2013-2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# FFI support for the Java language
#
# TODO support callbacks to super and casts
module java

import extern_classes
import c
import c_compiler_options

redef class FFILanguageAssignationPhase
	var java_language: FFILanguage = new JavaLanguage(self)
end

class JavaLanguage
	super FFILanguage

	redef fun identify_language(n) do return n.is_java

	redef fun compile_module_block(block, ccu, mmodule)
	do
		mmodule.ensure_java_files
		var java_file = mmodule.java_file
		assert java_file != null

		if block.is_inner_java then
			java_file.class_content.add(block.code)
		else java_file.header.add(block.code)
	end

	redef fun compile_extern_method(block, m, ccu, mmodule)
	do
		ffi_ccu = ccu
		mmodule.ensure_java_files
		var java_file = mmodule.java_file
		assert java_file != null

		var mclass_type = m.parent.as(AClassdef).mclass.mclass_type
		var mmethodef = m.mpropdef
		var mproperty = m.mpropdef.mproperty

		# C function calling the Java method through JNI
		var fc = new ExternCFunction(m, mmodule)

		fc.exprs.add """
	jclass java_class;
	jmethodID java_meth_id;

	// retrieve the current JVM
	Sys sys = Pointer_sys(NULL);
	JNIEnv *nit_ffi_jni_env = Sys_jni_env(sys);

	// retrieve the implementation Java class
	java_class = Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
	if (java_class == NULL) {
		PRINT_ERROR("Nit FFI with Java error: failed to load class.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}

	// register callbacks (only once per Nit module)
	if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
"""

		# Retrieve the Java implementation function id
		var java_fun_name = mproperty.build_cname(mclass_type, mmodule, "___java_impl", long_signature)
		var jni_format = mproperty.build_jni_format(mclass_type, mmodule)
		fc.exprs.add """
	// retreive the implementation static function
	java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
	if (java_meth_id == NULL) {
		PRINT_ERROR("Nit FFI with Java error: Java implementation not found.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}
"""

		# Call the C Java implementation method from C
		var signature = mmethodef.msignature
		assert signature != null

		var jni_signature_alt
		var return_type
		var params = new Array[String]
		params.add "nit_ffi_jni_env"
		params.add "java_class"
		params.add "java_meth_id"

		if mproperty.is_init then
			jni_signature_alt = mclass_type.jni_signature_alt
			return_type = mclass_type
		else
			params.add "self"
			if signature.return_mtype != null then
				var ret_mtype = signature.return_mtype
				ret_mtype = ret_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
				return_type = signature.return_mtype
				jni_signature_alt = return_type.jni_signature_alt
			else
				jni_signature_alt = "Void"
				return_type = null
			end
		end

		for p in signature.mparameters do
			var param_mtype = p.mtype
			param_mtype = param_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
			params.add(to_java_call_context.cast_to(param_mtype, p.name))
		end

		var cname = "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
		var ccall
		if return_type != null then
			ccall = "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
		else ccall = "{cname}({params.join(", ")});"

		fc.exprs.add """
	// execute implementation code
	{{{ccall}}}
	if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
		PRINT_ERROR("Nit FFI with Java error: Exception after call.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}

	(*nit_ffi_jni_env)->DeleteLocalRef(nit_ffi_jni_env, java_class);
"""

		if return_type != null then
			fc.exprs.add "\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
		end

		ccu.add_exported_function( fc )

		# Java implementation function in Java
		var java_csig = mproperty.build_csignature(mclass_type, mmodule, "___java_impl", long_signature, java_call_context)
		mmodule.java_file.class_content.add """
	public static {{{java_csig}}} {
		// from Nit FII at: {{{block.location}}}
		{{{block.code}}}
	}
"""

		mmodule.callbacks_used_from_java.join m.foreign_callbacks
	end

	redef fun compile_extern_class(block, m, ccu, mmodule) do end

	redef fun get_ftype(block, m) do return new ForeignJavaType(block.code)

	redef fun compile_to_files(mmodule, compdir)
	do
		# Make sure we have a .java file
		mmodule.ensure_java_files

		# Needed compiler and linker options
		mmodule.insert_compiler_options

		# Enable linking C callbacks to java native methods
		mmodule.ensure_linking_callback_methods(ffi_ccu.as(not null))

		# Java implementation code
		var java_file = mmodule.java_file
		assert java_file != null
		var extern_java_file = java_file.write_to_files(compdir)
		mmodule.ffi_files.add(extern_java_file)
	end

	var ffi_ccu: nullable CCompilationUnit = null # HACK

	redef fun compile_callback(callback, mmodule, mainmodule, ccu)
	do
		ffi_ccu = ccu
		callback.compile_callback_to_java(mmodule, mainmodule, ccu)
	end
end

redef class MModule
	private var callbacks_used_from_java = new ForeignCallbackSet

	# Pure java class source file
	private var java_file: nullable JavaClassTemplate = null

	# Set up the templates of the Java implementation class
	private fun ensure_java_files
	do
		if java_file != null then return

		# Java implementation code
		java_file = new JavaClassTemplate(impl_java_class_name)
	end

	# Compile C code to call JNI and link C callbacks implementations to Java extern methods
	private fun ensure_linking_callback_methods(ccu: CCompilationUnit)
	do
		var callbacks = callbacks_used_from_java.callbacks
		if callbacks.is_empty then
			ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 1;\n"<commit_msg>Java FFI: make `MModule::java_file` public<commit_after># This file is part of NIT ( http://www.nitlanguage.org ).
#
# Copyright 2013-2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# FFI support for the Java language
#
# TODO support callbacks to super and casts
module java

import extern_classes
import c
import c_compiler_options

redef class FFILanguageAssignationPhase
	var java_language: FFILanguage = new JavaLanguage(self)
end

class JavaLanguage
	super FFILanguage

	redef fun identify_language(n) do return n.is_java

	redef fun compile_module_block(block, ccu, mmodule)
	do
		mmodule.ensure_java_files
		var java_file = mmodule.java_file
		assert java_file != null

		if block.is_inner_java then
			java_file.class_content.add(block.code)
		else java_file.header.add(block.code)
	end

	redef fun compile_extern_method(block, m, ccu, mmodule)
	do
		ffi_ccu = ccu
		mmodule.ensure_java_files
		var java_file = mmodule.java_file
		assert java_file != null

		var mclass_type = m.parent.as(AClassdef).mclass.mclass_type
		var mmethodef = m.mpropdef
		var mproperty = m.mpropdef.mproperty

		# C function calling the Java method through JNI
		var fc = new ExternCFunction(m, mmodule)

		fc.exprs.add """
	jclass java_class;
	jmethodID java_meth_id;

	// retrieve the current JVM
	Sys sys = Pointer_sys(NULL);
	JNIEnv *nit_ffi_jni_env = Sys_jni_env(sys);

	// retrieve the implementation Java class
	java_class = Sys_load_jclass(sys, "{{{mmodule.impl_java_class_name}}}");
	if (java_class == NULL) {
		PRINT_ERROR("Nit FFI with Java error: failed to load class.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}

	// register callbacks (only once per Nit module)
	if (!nit_ffi_with_java_registered_natives) nit_ffi_with_java_register_natives(nit_ffi_jni_env, java_class);
"""

		# Retrieve the Java implementation function id
		var java_fun_name = mproperty.build_cname(mclass_type, mmodule, "___java_impl", long_signature)
		var jni_format = mproperty.build_jni_format(mclass_type, mmodule)
		fc.exprs.add """
	// retreive the implementation static function
	java_meth_id = (*nit_ffi_jni_env)->GetStaticMethodID(nit_ffi_jni_env, java_class, "{{{java_fun_name}}}", "{{{jni_format}}}");
	if (java_meth_id == NULL) {
		PRINT_ERROR("Nit FFI with Java error: Java implementation not found.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}
"""

		# Call the C Java implementation method from C
		var signature = mmethodef.msignature
		assert signature != null

		var jni_signature_alt
		var return_type
		var params = new Array[String]
		params.add "nit_ffi_jni_env"
		params.add "java_class"
		params.add "java_meth_id"

		if mproperty.is_init then
			jni_signature_alt = mclass_type.jni_signature_alt
			return_type = mclass_type
		else
			params.add "self"
			if signature.return_mtype != null then
				var ret_mtype = signature.return_mtype
				ret_mtype = ret_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
				return_type = signature.return_mtype
				jni_signature_alt = return_type.jni_signature_alt
			else
				jni_signature_alt = "Void"
				return_type = null
			end
		end

		for p in signature.mparameters do
			var param_mtype = p.mtype
			param_mtype = param_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
			params.add(to_java_call_context.cast_to(param_mtype, p.name))
		end

		var cname = "(*nit_ffi_jni_env)->CallStatic{jni_signature_alt}Method"
		var ccall
		if return_type != null then
			ccall = "{return_type.jni_type} jni_res = {cname}({params.join(", ")});"
		else ccall = "{cname}({params.join(", ")});"

		fc.exprs.add """
	// execute implementation code
	{{{ccall}}}
	if ((*nit_ffi_jni_env)->ExceptionCheck(nit_ffi_jni_env)) {
		PRINT_ERROR("Nit FFI with Java error: Exception after call.\\n");
		(*nit_ffi_jni_env)->ExceptionDescribe(nit_ffi_jni_env);
		exit(1);
	}

	(*nit_ffi_jni_env)->DeleteLocalRef(nit_ffi_jni_env, java_class);
"""

		if return_type != null then
			fc.exprs.add "\treturn {to_java_call_context.cast_from(return_type, "jni_res")};"
		end

		ccu.add_exported_function( fc )

		# Java implementation function in Java
		var java_csig = mproperty.build_csignature(mclass_type, mmodule, "___java_impl", long_signature, java_call_context)
		mmodule.java_file.class_content.add """
	public static {{{java_csig}}} {
		// from Nit FII at: {{{block.location}}}
		{{{block.code}}}
	}
"""

		mmodule.callbacks_used_from_java.join m.foreign_callbacks
	end

	redef fun compile_extern_class(block, m, ccu, mmodule) do end

	redef fun get_ftype(block, m) do return new ForeignJavaType(block.code)

	redef fun compile_to_files(mmodule, compdir)
	do
		# Make sure we have a .java file
		mmodule.ensure_java_files

		# Needed compiler and linker options
		mmodule.insert_compiler_options

		# Enable linking C callbacks to java native methods
		mmodule.ensure_linking_callback_methods(ffi_ccu.as(not null))

		# Java implementation code
		var java_file = mmodule.java_file
		assert java_file != null
		var extern_java_file = java_file.write_to_files(compdir)
		mmodule.ffi_files.add(extern_java_file)
	end

	var ffi_ccu: nullable CCompilationUnit = null # HACK

	redef fun compile_callback(callback, mmodule, mainmodule, ccu)
	do
		ffi_ccu = ccu
		callback.compile_callback_to_java(mmodule, mainmodule, ccu)
	end
end

redef class MModule
	private var callbacks_used_from_java = new ForeignCallbackSet

	# Java source file extracted from user FFI code with generated structure
	var java_file: nullable JavaClassTemplate = null

	# Set up the templates of the Java implementation class
	private fun ensure_java_files
	do
		if java_file != null then return

		# Java implementation code
		java_file = new JavaClassTemplate(impl_java_class_name)
	end

	# Compile C code to call JNI and link C callbacks implementations to Java extern methods
	private fun ensure_linking_callback_methods(ccu: CCompilationUnit)
	do
		var callbacks = callbacks_used_from_java.callbacks
		if callbacks.is_empty then
			ccu.body_decl.add "static int nit_ffi_with_java_registered_natives = 1;\n"
{'fraction_non_alphanumeric': 0.08853532277710109, 'fraction_numerical': 0.00243605359317905, 'mean_word_length': 4.869973190348525, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6912544', 'n_tokens_mistral': 4879, 'n_tokens_neox': 4545, 'n_words': 1166}