Bindings updates
[ldk-java] / java_strings.py
index 0a479de3c594402c97d5e780057ae58fa1ba8669..587d8281ccf84e7b1e7618f7fb5c424960729482 100644 (file)
@@ -1,12 +1,54 @@
 from bindingstypes import *
 
 class Consts:
-    def __init__(self, DEBUG):
-
+    def __init__(self, DEBUG: bool, **kwargs):
+        self.c_array_class_caches = set()
         self.c_type_map = dict(
-            byte = ['byte'],
+            uint8_t = ['byte'],
+            uint16_t = ['short'],
+            uint32_t = ['int'],
+            uint64_t = ['long'],
+        )
+
+        self.to_hu_conv_templates = dict(
+            ptr = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});',
+            default = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});'
         )
 
+        self.bindings_header = """package org.ldk.impl;
+import org.ldk.enums.*;
+
+public class bindings {
+       public static class VecOrSliceDef {
+               public long dataptr;
+               public long datalen;
+               public long stride;
+               public VecOrSliceDef(long dataptr, long datalen, long stride) {
+                       this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
+               }
+       }
+       static {
+               System.loadLibrary(\"lightningjni\");
+               init(java.lang.Enum.class, VecOrSliceDef.class);
+               init_class_cache();
+       }
+       static native void init(java.lang.Class c, java.lang.Class slicedef);
+       static native void init_class_cache();
+
+       public static native boolean deref_bool(long ptr);
+       public static native long deref_long(long ptr);
+       public static native void free_heap_ptr(long ptr);
+       public static native byte[] read_bytes(long ptr, long len);
+       public static native byte[] get_u8_slice_bytes(long slice_ptr);
+       public static native long bytes_to_u8_vec(byte[] bytes);
+       public static native long new_txpointer_copy_data(byte[] txdata);
+       public static native void txpointer_free(long ptr);
+       public static native byte[] txpointer_get_buffer(long ptr);
+       public static native long vec_slice_len(long vec);
+       public static native long new_empty_slice_vec();
+
+"""
+
         self.common_base = """package org.ldk.structs;
 import java.util.LinkedList;
 class CommonBase {
@@ -255,15 +297,21 @@ import java.util.Arrays;
         self.ptr_c_ty = "int64_t"
         self.ptr_native_ty = "long"
         self.result_c_ty = "jclass"
+        self.owned_str_to_c_call = ("(*env)->NewStringUTF(env, ", ")")
         self.ptr_arr = "jobjectArray"
         self.get_native_arr_len_call = ("(*env)->GetArrayLength(env, ", ")")
-        self.get_native_arr_ptr_call = ("(*env)->GetPrimitiveArrayCritical(env, ", ", NULL)")
 
-    def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
-        return "(*env)->ReleasePrimitiveArrayCritical(env, " + arr_var + ", " + arr_ptr_var + ", 0)"
+    def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
+        if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
+            return "(*env)->ReleasePrimitiveArrayCritical(env, " + arr_var + ", " + arr_ptr_var + ", 0)"
+        return None
     def create_native_arr_call(self, arr_len, ty_info):
         if ty_info.c_ty == "int8_tArray":
             return "(*env)->NewByteArray(env, " + arr_len + ")"
+        elif ty_info.subty.c_ty.endswith("Array"):
+            clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
+            self.c_array_class_caches.add(clz_var)
+            return "(*env)->NewObjectArray(env, " + arr_len + ", " + clz_var + "_clz, NULL);\n"
         else:
             return "(*env)->New" + ty_info.java_ty.strip("[]").title() + "Array(env, " + arr_len + ")"
     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
@@ -286,18 +334,26 @@ import java.util.Arrays;
             return "(*env)->GetObjectArrayElement(env, " + arr_name + ", " + idxc + ")"
         else:
             assert False # Only called if above is None
+    def get_native_arr_ptr_call(self, ty_info):
+        if ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"):
+            return None
+        return ("(*env)->GetPrimitiveArrayCritical(env, ", ", NULL)")
+    def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
+        if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
+            return None
+        return "(*env)->SetObjectArrayElement(env, " + arr_name + ", " + idxc + ", " + entry_access + ")"
     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
         if ty_info.c_ty == "int8_tArray":
             return "(*env)->ReleaseByteArrayElements(env, " + arr_name + ", (int8_t*)" + dest_name + ", 0);"
         else:
             return "(*env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements(env, " + arr_name + ", " + dest_name + ", 0)"
 
-    def init_str(self, c_array_class_caches):
+    def init_str(self):
         res = ""
-        for ty in c_array_class_caches:
+        for ty in self.c_array_class_caches:
             res = res + "static jclass " + ty + "_clz = NULL;\n"
         res = res + "JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass clz) {\n"
-        for ty in c_array_class_caches:
+        for ty in self.c_array_class_caches:
             res = res + "\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n"
             res = res + "\tCHECK(" + ty + "_clz != NULL);\n"
             res = res + "\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n"
@@ -503,7 +559,6 @@ import java.util.Arrays;
             else:
                 out_java = out_java + ", " + var[0] + " " + var[1]
         out_java = out_java + ");\n"
-        out_java = out_java + "\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n"
 
         # Now that we've written out our java code (and created java_meths), generate C
         out_c = "typedef struct " + struct_name + "_JCalls {\n"
@@ -652,14 +707,14 @@ import java.util.Arrays;
         out_c = out_c + "\treturn (long)res_ptr;\n"
         out_c = out_c + "}\n"
 
-        out_c = out_c + self.c_fn_ty_pfx + "jobject " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " val) {\n"
-        out_c = out_c + "\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n"
-        out_c = out_c + "\tCHECK(ret != NULL);\n"
-        out_c = out_c + "\treturn ret;\n"
-        out_c = out_c + "}\n"
-
         return (out_java, out_java_trait, out_c)
 
+    def trait_struct_inc_refcnt(self, ty_info):
+        base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
+        base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
+        base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
+        return base_conv
+
     def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
         java_hu_type = struct_name.replace("LDK", "")
         out_java_enum = ""
@@ -743,3 +798,21 @@ import java.util.Arrays;
         out_c += ("\t}\n}\n")
         out_java_enum += ("}\n")
         return (out_java, out_java_enum, out_c)
+
+    def map_opaque_struct(self, struct_name):
+        out_opaque_struct_human = ""
+        out_opaque_struct_human += self.hu_struct_file_prefix
+        out_opaque_struct_human += ("public class " + struct_name.replace("LDK","") + " extends CommonBase")
+        if struct_name.startswith("LDKLocked"):
+            out_opaque_struct_human += (" implements AutoCloseable")
+        out_opaque_struct_human += (" {\n")
+        out_opaque_struct_human += ("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
+        if struct_name.startswith("LDKLocked"):
+            out_opaque_struct_human += ("\t@Override public void close() {\n")
+        else:
+            out_opaque_struct_human += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
+            out_opaque_struct_human += ("\tprotected void finalize() throws Throwable {\n")
+            out_opaque_struct_human += ("\t\tsuper.finalize();\n")
+        out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
+        out_opaque_struct_human += ("\t}\n\n")
+        return out_opaque_struct_human