1 from bindingstypes import *
4 def __init__(self, DEBUG: bool, **kwargs):
5 self.c_array_class_caches = set()
6 self.c_type_map = dict(
13 self.to_hu_conv_templates = dict(
14 ptr = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});',
15 default = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});'
18 self.bindings_header = """package org.ldk.impl;
19 import org.ldk.enums.*;
21 public class bindings {
22 public static class VecOrSliceDef {
26 public VecOrSliceDef(long dataptr, long datalen, long stride) {
27 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
31 System.loadLibrary(\"lightningjni\");
32 init(java.lang.Enum.class, VecOrSliceDef.class);
35 static native void init(java.lang.Class c, java.lang.Class slicedef);
36 static native void init_class_cache();
38 public static native boolean deref_bool(long ptr);
39 public static native long deref_long(long ptr);
40 public static native void free_heap_ptr(long ptr);
41 public static native byte[] read_bytes(long ptr, long len);
42 public static native byte[] get_u8_slice_bytes(long slice_ptr);
43 public static native long bytes_to_u8_vec(byte[] bytes);
44 public static native long new_txpointer_copy_data(byte[] txdata);
45 public static native void txpointer_free(long ptr);
46 public static native byte[] txpointer_get_buffer(long ptr);
47 public static native long vec_slice_len(long vec);
48 public static native long new_empty_slice_vec();
52 self.bindings_footer = "}\n"
54 self.common_base = """package org.ldk.structs;
55 import java.util.LinkedList;
58 LinkedList<Object> ptrs_to = new LinkedList();
59 protected CommonBase(long ptr) { this.ptr = ptr; }
60 public long _test_only_get_ptr() { return this.ptr; }
64 self.c_file_pfx = """#include \"org_ldk_impl_bindings.h\"
65 #include <rust_types.h>
66 #include <lightning.h>
68 #include <stdatomic.h>
73 self.c_file_pfx = self.c_file_pfx + """#define MALLOC(a, _) malloc(a)
74 #define FREE(p) if ((long)(p) > 1024) { free(p); }
75 #define DO_ASSERT(a) (void)(a)
79 self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
80 // Always run a, then assert it is true:
81 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
82 // Assert a is true or do nothing
83 #define CHECK(a) DO_ASSERT(a)
85 // Running a leak check across all the allocations and frees of the JDK is a mess,
86 // so instead we implement our own naive leak checker here, relying on the -wrap
87 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
88 // and free'd in Rust or C across the generated bindings shared library.
92 static mtx_t allocation_mtx;
94 void __attribute__((constructor)) init_mtx() {
95 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
99 typedef struct allocation {
100 struct allocation* next;
102 const char* struct_name;
106 static allocation* allocation_ll = NULL;
108 void* __real_malloc(size_t len);
109 void* __real_calloc(size_t nmemb, size_t len);
110 static void new_allocation(void* res, const char* struct_name) {
111 allocation* new_alloc = __real_malloc(sizeof(allocation));
112 new_alloc->ptr = res;
113 new_alloc->struct_name = struct_name;
114 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
115 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
116 new_alloc->next = allocation_ll;
117 allocation_ll = new_alloc;
118 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
120 static void* MALLOC(size_t len, const char* struct_name) {
121 void* res = __real_malloc(len);
122 new_allocation(res, struct_name);
125 void __real_free(void* ptr);
126 static void alloc_freed(void* ptr) {
127 allocation* p = NULL;
128 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
129 allocation* it = allocation_ll;
130 while (it->ptr != ptr) {
131 p = it; it = it->next;
133 fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
135 int bt_len = backtrace(bt, BT_MAX);
136 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
137 fprintf(stderr, "\\n\\n");
138 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
139 return; // addrsan should catch malloc-unknown and print more info than we have
142 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
143 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
144 DO_ASSERT(it->ptr == ptr);
147 static void FREE(void* ptr) {
148 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
153 void* __wrap_malloc(size_t len) {
154 void* res = __real_malloc(len);
155 new_allocation(res, "malloc call");
158 void* __wrap_calloc(size_t nmemb, size_t len) {
159 void* res = __real_calloc(nmemb, len);
160 new_allocation(res, "calloc call");
163 void __wrap_free(void* ptr) {
164 if (ptr == NULL) return;
169 void* __real_realloc(void* ptr, size_t newlen);
170 void* __wrap_realloc(void* ptr, size_t len) {
171 if (ptr != NULL) alloc_freed(ptr);
172 void* res = __real_realloc(ptr, len);
173 new_allocation(res, "realloc call");
176 void __wrap_reallocarray(void* ptr, size_t new_sz) {
177 // Rust doesn't seem to use reallocarray currently
181 void __attribute__((destructor)) check_leaks() {
182 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
183 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
184 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
185 fprintf(stderr, "\\n\\n");
187 DO_ASSERT(allocation_ll == NULL);
190 self.c_file_pfx = self.c_file_pfx + """
191 static jmethodID ordinal_meth = NULL;
192 static jmethodID slicedef_meth = NULL;
193 static jclass slicedef_cls = NULL;
194 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
195 ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
196 CHECK(ordinal_meth != NULL);
197 slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
198 CHECK(slicedef_meth != NULL);
199 slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
200 CHECK(slicedef_cls != NULL);
203 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
204 return *((bool*)ptr);
206 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
207 return *((long*)ptr);
209 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
212 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * env, jclass _b, jlong ptr, jlong len) {
213 jbyteArray ret_arr = (*env)->NewByteArray(env, len);
214 (*env)->SetByteArrayRegion(env, ret_arr, 0, len, (unsigned char*)ptr);
217 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * env, jclass _b, jlong slice_ptr) {
218 LDKu8slice *slice = (LDKu8slice*)slice_ptr;
219 jbyteArray ret_arr = (*env)->NewByteArray(env, slice->datalen);
220 (*env)->SetByteArrayRegion(env, ret_arr, 0, slice->datalen, slice->data);
223 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * env, jclass _b, jbyteArray bytes) {
224 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
225 vec->datalen = (*env)->GetArrayLength(env, bytes);
226 vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
227 (*env)->GetByteArrayRegion (env, bytes, 0, vec->datalen, vec->data);
230 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_txpointer_1get_1buffer (JNIEnv * env, jclass _b, jlong ptr) {
231 LDKTransaction *txdata = (LDKTransaction*)ptr;
233 slice.data = txdata->data;
234 slice.datalen = txdata->datalen;
235 return Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes(env, _b, (long)&slice);
237 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
238 LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
239 txdata->datalen = (*env)->GetArrayLength(env, bytes);
240 txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
241 txdata->data_is_owned = false;
242 (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
245 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
246 LDKTransaction *tx = (LDKTransaction*)ptr;
247 tx->data_is_owned = true;
248 Transaction_free(*tx);
251 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
252 // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
253 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
254 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
255 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
256 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
257 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
258 return (long)vec->datalen;
260 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * env, jclass _b) {
261 // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
262 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
263 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
264 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
265 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
266 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
272 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
273 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
274 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
275 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
277 _Static_assert(sizeof(jlong) == sizeof(int64_t), "We assume that j-types are the same as C types");
278 _Static_assert(sizeof(jbyte) == sizeof(char), "We assume that j-types are the same as C types");
279 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
281 typedef jlongArray int64_tArray;
282 typedef jbyteArray int8_tArray;
286 self.hu_struct_file_prefix = """package org.ldk.structs;
288 import org.ldk.impl.bindings;
289 import org.ldk.enums.*;
290 import org.ldk.util.*;
291 import java.util.Arrays;
293 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
295 self.c_fn_ty_pfx = "JNIEXPORT "
296 self.c_fn_name_pfx = "JNICALL Java_org_ldk_impl_bindings_"
297 self.c_fn_args_pfx = "JNIEnv *env, jclass clz"
298 self.file_ext = ".java"
299 self.ptr_c_ty = "int64_t"
300 self.ptr_native_ty = "long"
301 self.result_c_ty = "jclass"
302 self.owned_str_to_c_call = ("(*env)->NewStringUTF(env, ", ")")
303 self.ptr_arr = "jobjectArray"
304 self.get_native_arr_len_call = ("(*env)->GetArrayLength(env, ", ")")
306 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
307 if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
308 return "(*env)->ReleasePrimitiveArrayCritical(env, " + arr_var + ", " + arr_ptr_var + ", 0)"
310 def create_native_arr_call(self, arr_len, ty_info):
311 if ty_info.c_ty == "int8_tArray":
312 return "(*env)->NewByteArray(env, " + arr_len + ")"
313 elif ty_info.subty.c_ty.endswith("Array"):
314 clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
315 self.c_array_class_caches.add(clz_var)
316 return "(*env)->NewObjectArray(env, " + arr_len + ", " + clz_var + "_clz, NULL);\n"
318 return "(*env)->New" + ty_info.java_ty.strip("[]").title() + "Array(env, " + arr_len + ")"
319 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
320 if ty_info.c_ty == "int8_tArray":
321 return ("(*env)->SetByteArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", ", ")")
324 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
325 if ty_info.c_ty == "int8_tArray":
327 return "(*env)->GetByteArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", " + dest_name + ")"
329 return "(*env)->GetByteArrayElements (env, " + arr_name + ", NULL)"
330 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
331 return "(*env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (env, " + arr_name + ", NULL)"
334 def get_native_arr_elem(self, arr_name, idxc, ty_info):
335 if self.get_native_arr_contents(arr_name, "", "", ty_info, False) is None:
336 return "(*env)->GetObjectArrayElement(env, " + arr_name + ", " + idxc + ")"
338 assert False # Only called if above is None
339 def get_native_arr_ptr_call(self, ty_info):
340 if ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"):
342 return ("(*env)->GetPrimitiveArrayCritical(env, ", ", NULL)")
343 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
344 if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
346 return "(*env)->SetObjectArrayElement(env, " + arr_name + ", " + idxc + ", " + entry_access + ")"
347 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
348 if ty_info.c_ty == "int8_tArray":
349 return "(*env)->ReleaseByteArrayElements(env, " + arr_name + ", (int8_t*)" + dest_name + ", 0);"
351 return "(*env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements(env, " + arr_name + ", " + dest_name + ", 0)"
355 for ty in self.c_array_class_caches:
356 res = res + "static jclass " + ty + "_clz = NULL;\n"
357 res = res + "JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass clz) {\n"
358 for ty in self.c_array_class_caches:
359 res = res + "\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n"
360 res = res + "\tCHECK(" + ty + "_clz != NULL);\n"
361 res = res + "\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n"
365 def native_c_unitary_enum_map(self, struct_name, variants):
366 out_java_enum = "package org.ldk.enums;\n\n"
369 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_from_java(" + self.c_fn_args_pfx + ") {\n"
370 out_c = out_c + "\tswitch ((*env)->CallIntMethod(env, clz, ordinal_meth)) {\n"
372 out_java_enum = out_java_enum + "public enum " + struct_name + " {\n"
375 out_java_enum = out_java_enum + "\t" + var + ",\n"
376 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
378 out_java_enum = out_java_enum + "\t; static native void init();\n"
379 out_java_enum = out_java_enum + "\tstatic { init(); }\n"
380 out_java_enum = out_java_enum + "}"
381 out_java = out_java + "\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n"
382 out_c = out_c + "\t}\n"
383 out_c = out_c + "\tabort();\n"
384 out_c = out_c + "}\n"
386 out_c = out_c + "static jclass " + struct_name + "_class = NULL;\n"
388 out_c = out_c + "static jfieldID " + struct_name + "_" + var + " = NULL;\n"
389 out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
390 out_c = out_c + "\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n"
391 out_c = out_c + "\tCHECK(" + struct_name + "_class != NULL);\n"
393 out_c = out_c + "\t" + struct_name + "_" + var + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + var + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n"
394 out_c = out_c + "\tCHECK(" + struct_name + "_" + var + " != NULL);\n"
395 out_c = out_c + "}\n"
396 out_c = out_c + "static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n"
397 out_c = out_c + "\tswitch (val) {\n"
400 out_c = out_c + "\t\tcase " + var + ":\n"
401 out_c = out_c + "\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + var + ");\n"
403 out_c = out_c + "\t\tdefault: abort();\n"
404 out_c = out_c + "\t}\n"
405 out_c = out_c + "}\n\n"
407 return (out_c, out_java_enum, out_java)
409 def c_unitary_enum_to_native_call(self, ty_info):
410 return (ty_info.rust_obj + "_to_java(env, ", ")")
411 def native_unitary_enum_to_c_call(self, ty_info):
412 return (ty_info.rust_obj + "_from_java(env, ", ")")
414 def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
417 out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
418 out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
419 out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
420 for var_name in variants:
421 out_c = out_c + "\t" + struct_name + "_" + var_name + "_class =\n"
422 out_c = out_c + "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n"
423 out_c = out_c + "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
424 out_c = out_c + "\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n"
425 out_c = out_c + "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
426 out_c = out_c + "}\n"
429 def c_complex_enum_pass_ty(self, struct_name):
432 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
433 ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
434 for param in c_params:
435 ret = ret + ", " + param
438 def native_c_map_trait(self, struct_name, field_vars, field_fns):
442 # First generate most of the Java code, note that we need information about java method argument strings for C
443 out_java_trait = out_java_trait + self.hu_struct_file_prefix
444 out_java_trait = out_java_trait + "public class " + struct_name.replace("LDK","") + " extends CommonBase {\n"
445 out_java_trait = out_java_trait + "\tfinal bindings." + struct_name + " bindings_instance;\n"
446 out_java_trait = out_java_trait + "\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n"
447 out_java_trait = out_java_trait + "\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg"
448 for var in field_vars:
449 if isinstance(var, ConvInfo):
450 out_java_trait = out_java_trait + ", " + var.java_hu_ty + " " + var.arg_name
452 out_java_trait = out_java_trait + ", bindings." + var[0] + " " + var[1]
453 out_java_trait = out_java_trait + ") {\n"
454 out_java_trait = out_java_trait + "\t\tsuper(bindings." + struct_name + "_new(arg"
455 for var in field_vars:
456 if isinstance(var, ConvInfo):
457 if var.from_hu_conv is not None:
458 out_java_trait = out_java_trait + ", " + var.from_hu_conv[0]
460 out_java_trait = out_java_trait + ", " + var.arg_name
462 out_java_trait = out_java_trait + ", " + var[1]
463 out_java_trait = out_java_trait + "));\n"
464 out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(arg);\n"
465 for var in field_vars:
466 if isinstance(var, ConvInfo):
467 if var.from_hu_conv is not None and var.from_hu_conv[1] != "":
468 out_java_trait = out_java_trait + "\t\t" + var.from_hu_conv[1] + ";\n"
470 out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(" + var[1] + ");\n"
471 out_java_trait = out_java_trait + "\t\tthis.bindings_instance = arg;\n"
472 out_java_trait = out_java_trait + "\t}\n"
473 out_java_trait = out_java_trait + "\t@Override @SuppressWarnings(\"deprecation\")\n"
474 out_java_trait = out_java_trait + "\tprotected void finalize() throws Throwable {\n"
475 out_java_trait = out_java_trait + "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n"
476 out_java_trait = out_java_trait + "\t}\n\n"
478 java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
479 java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
480 for var in field_vars:
481 if isinstance(var, ConvInfo):
482 java_trait_constr = java_trait_constr + ", " + var.java_hu_ty + " " + var.arg_name
484 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
485 # Java-implemented version, so we require users pass a Java implementation here :/
486 java_trait_constr = java_trait_constr + ", " + var[0].replace("LDK", "") + "." + var[0].replace("LDK", "") + "Interface " + var[1] + "_impl"
487 java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
488 java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
489 out_java_trait = out_java_trait + "\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n"
490 out_java = out_java + "\tpublic interface " + struct_name + " {\n"
492 for fn_line in field_fns:
493 java_meth_descr = "("
494 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
495 out_java = out_java + "\t\t " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
496 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
497 out_java_trait = out_java_trait + "\t\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
499 for idx, arg_conv_info in enumerate(fn_line.args_ty):
501 out_java = out_java + ", "
502 java_trait_constr = java_trait_constr + ", "
503 out_java_trait = out_java_trait + ", "
504 out_java = out_java + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
505 out_java_trait = out_java_trait + arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name
506 java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
507 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
508 java_meth_descr = java_meth_descr + ")" + fn_line.ret_ty_info.java_fn_ty_arg
509 java_meths.append((fn_line.fn_name, java_meth_descr))
511 out_java = out_java + ");\n"
512 out_java_trait = out_java_trait + ");\n"
513 java_trait_constr = java_trait_constr + ") {\n"
515 for arg_info in fn_line.args_ty:
516 if arg_info.to_hu_conv is not None:
517 java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
519 if fn_line.ret_ty_info.java_ty != "void":
520 java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
522 java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.fn_name + "("
524 for idx, arg_info in enumerate(fn_line.args_ty):
526 java_trait_constr = java_trait_constr + ", "
527 if arg_info.to_hu_conv_name is not None:
528 java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
530 java_trait_constr = java_trait_constr + arg_info.arg_name
532 java_trait_constr = java_trait_constr + ");\n"
533 if fn_line.ret_ty_info.java_ty != "void":
534 if fn_line.ret_ty_info.from_hu_conv is not None:
535 java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
536 if fn_line.ret_ty_info.from_hu_conv[1] != "":
537 java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
538 #if fn_line.ret_ty_info.rust_obj in result_types:
539 # XXX: We need to handle this in conversion logic so that its cross-language!
540 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
541 # java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
542 java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
544 java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
545 java_trait_constr = java_trait_constr + "\t\t\t}\n"
546 java_trait_constr = java_trait_constr + "\t\t}"
547 for var in field_vars:
548 if isinstance(var, ConvInfo):
549 java_trait_constr = java_trait_constr + ", " + var.arg_name
551 java_trait_constr = java_trait_constr + ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
552 out_java_trait = out_java_trait + "\t}\n"
553 out_java_trait = out_java_trait + java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n"
555 out_java = out_java + "\t}\n"
557 out_java = out_java + "\tpublic static native long " + struct_name + "_new(" + struct_name + " impl"
558 for var in field_vars:
559 if isinstance(var, ConvInfo):
560 out_java = out_java + ", " + var.java_ty + " " + var.arg_name
562 out_java = out_java + ", " + var[0] + " " + var[1]
563 out_java = out_java + ");\n"
565 # Now that we've written out our java code (and created java_meths), generate C
566 out_c = "typedef struct " + struct_name + "_JCalls {\n"
567 out_c = out_c + "\tatomic_size_t refcnt;\n"
568 out_c = out_c + "\tJavaVM *vm;\n"
569 out_c = out_c + "\tjweak o;\n"
570 for var in field_vars:
571 if isinstance(var, ConvInfo):
572 # We're a regular ol' field
576 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
578 if fn.fn_name != "free" and fn.fn_name != "clone":
579 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
580 out_c = out_c + "} " + struct_name + "_JCalls;\n"
582 for fn_line in field_fns:
583 if fn_line.fn_name == "free":
584 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
585 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
586 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
587 out_c = out_c + "\t\tJNIEnv *env;\n"
588 out_c = out_c + "\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
589 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
590 out_c = out_c + "\t\tFREE(j_calls);\n"
591 out_c = out_c + "\t}\n}\n"
593 for idx, fn_line in enumerate(field_fns):
594 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
595 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
596 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
597 if fn_line.self_is_const:
598 out_c = out_c + "const void* this_arg"
600 out_c = out_c + "void* this_arg"
602 for idx, arg in enumerate(fn_line.args_ty):
603 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
605 out_c = out_c + ") {\n"
606 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
607 out_c = out_c + "\tJNIEnv *env;\n"
608 out_c = out_c + "\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
610 for arg_info in fn_line.args_ty:
611 if arg_info.ret_conv is not None:
612 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
613 out_c = out_c + arg_info.arg_name
614 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
616 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
617 if fn_line.ret_ty_info.c_ty.endswith("Array"):
618 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
619 elif not fn_line.ret_ty_info.passed_as_ptr:
620 out_c = out_c + "\treturn (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
622 out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret = (" + fn_line.ret_ty_info.rust_obj + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
624 for idx, arg_info in enumerate(fn_line.args_ty):
625 if arg_info.ret_conv is not None:
626 out_c = out_c + ", " + arg_info.ret_conv_name
628 out_c = out_c + ", " + arg_info.arg_name
629 out_c = out_c + ");\n"
630 if fn_line.ret_ty_info.arg_conv is not None:
631 out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
633 out_c = out_c + "}\n"
635 # Write out a clone function whether we need one or not, as we use them in moving to rust
636 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
637 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
638 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
639 for var in field_vars:
640 if not isinstance(var, ConvInfo):
641 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
642 out_c = out_c + "\treturn (void*) this_arg;\n"
643 out_c = out_c + "}\n"
645 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
646 for var in field_vars:
647 if isinstance(var, ConvInfo):
648 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
650 out_c = out_c + ", jobject " + var[1]
651 out_c = out_c + ") {\n"
653 out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
654 out_c = out_c + "\tCHECK(c != NULL);\n"
655 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
656 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
657 out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
658 out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
660 for (fn_name, java_meth_descr) in java_meths:
661 if fn_name != "free" and fn_name != "clone":
662 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
663 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
665 for var in field_vars:
666 if isinstance(var, ConvInfo) and var.arg_conv is not None:
667 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
668 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
669 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
670 for fn_line in field_fns:
671 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
672 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
673 elif fn_line.fn_name == "free":
674 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
676 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
677 for var in field_vars:
678 if isinstance(var, ConvInfo):
679 if var.arg_conv_name is not None:
680 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
681 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
683 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
684 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
686 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1] + "),\n"
687 out_c = out_c + "\t};\n"
688 for var in field_vars:
689 if not isinstance(var, ConvInfo):
690 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
691 out_c = out_c + "\treturn ret;\n"
692 out_c = out_c + "}\n"
694 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new (" + self.c_fn_args_pfx + ", jobject o"
695 for var in field_vars:
696 if isinstance(var, ConvInfo):
697 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
699 out_c = out_c + ", jobject " + var[1]
700 out_c = out_c + ") {\n"
701 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
702 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
703 for var in field_vars:
704 if isinstance(var, ConvInfo):
705 out_c = out_c + ", " + var.arg_name
707 out_c = out_c + ", " + var[1]
708 out_c = out_c + ");\n"
709 out_c = out_c + "\treturn (long)res_ptr;\n"
710 out_c = out_c + "}\n"
712 return (out_java, out_java_trait, out_c)
714 def trait_struct_inc_refcnt(self, ty_info):
715 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
716 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
717 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
720 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
721 java_hu_type = struct_name.replace("LDK", "")
726 out_java_enum += (self.hu_struct_file_prefix)
727 out_java_enum += ("public class " + java_hu_type + " extends CommonBase {\n")
728 out_java_enum += ("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
729 out_java_enum += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
730 out_java_enum += ("\tprotected void finalize() throws Throwable {\n")
731 out_java_enum += ("\t\tsuper.finalize();\n")
732 out_java_enum += ("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
733 out_java_enum += ("\t}\n")
734 out_java_enum += ("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
735 out_java_enum += ("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
736 java_hu_subclasses = ""
738 init_meth_jty_strs = {}
740 out_java += ("\tpublic static class " + struct_name + " {\n")
741 out_java += ("\t\tprivate " + struct_name + "() {}\n")
742 for var in variant_list:
743 out_java += ("\t\tpublic final static class " + var.var_name + " extends " + struct_name + " {\n")
744 java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var.var_name + " extends " + java_hu_type + " {\n"
745 out_java_enum += ("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var.var_name + ".class) {\n")
746 out_java_enum += ("\t\t\treturn new " + var.var_name + "(ptr, (bindings." + struct_name + "." + var.var_name + ")raw_val);\n")
747 init_meth_jty_str = ""
748 init_meth_params = ""
751 for idx, field_ty in enumerate(var.fields):
752 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
753 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
754 if field_ty.to_hu_conv is not None:
755 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
756 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
757 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
759 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
760 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
762 init_meth_params = init_meth_params + ", "
763 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
764 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
765 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
766 out_java += (init_meth_body)
768 out_java += ("\t\t}\n")
769 out_java_enum += ("\t\t}\n")
770 java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var.var_name + "(long ptr, bindings." + struct_name + "." + var.var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
771 java_hu_subclasses = java_hu_subclasses + hu_conv_body
772 java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
773 init_meth_jty_strs[var.var_name] = init_meth_jty_str
774 out_java += ("\t\tstatic native void init();\n")
775 out_java += ("\t}\n")
776 out_java_enum += ("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
777 out_java_enum += (java_hu_subclasses)
778 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
779 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
781 out_c += (self.c_complex_enum_pfx(struct_name, [x.var_name for x in variant_list], init_meth_jty_strs))
783 out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
784 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
785 out_c += ("\tswitch(obj->tag) {\n")
786 for var in variant_list:
787 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
789 for idx, field_map in enumerate(var.fields):
790 if field_map.ret_conv is not None:
791 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
792 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
793 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
794 c_params.append(field_map.ret_conv_name)
796 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
797 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
799 out_c += ("\t\tdefault: abort();\n")
800 out_c += ("\t}\n}\n")
801 out_java_enum += ("}\n")
802 return (out_java, out_java_enum, out_c)
804 def map_opaque_struct(self, struct_name):
805 out_opaque_struct_human = ""
806 out_opaque_struct_human += self.hu_struct_file_prefix
807 out_opaque_struct_human += ("public class " + struct_name.replace("LDK","") + " extends CommonBase")
808 if struct_name.startswith("LDKLocked"):
809 out_opaque_struct_human += (" implements AutoCloseable")
810 out_opaque_struct_human += (" {\n")
811 out_opaque_struct_human += ("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
812 if struct_name.startswith("LDKLocked"):
813 out_opaque_struct_human += ("\t@Override public void close() {\n")
815 out_opaque_struct_human += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
816 out_opaque_struct_human += ("\tprotected void finalize() throws Throwable {\n")
817 out_opaque_struct_human += ("\t\tsuper.finalize();\n")
818 out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
819 out_opaque_struct_human += ("\t}\n\n")
820 return out_opaque_struct_human
823 def map_function(self, argument_types, c_call_string, is_free, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, args_known, has_out_java_struct: bool, type_mapping_generator):
826 out_java_struct = None
828 out_java += ("\tpublic static native ")
829 out_c += (self.c_fn_ty_pfx)
830 out_c += (return_type_info.c_ty)
831 out_java += (return_type_info.java_ty)
832 if return_type_info.ret_conv is not None:
833 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
834 out_java += (" " + method_name + "(")
835 out_c += (" " + self.c_fn_name_pfx + method_name.replace('_', '_1') + "(" + self.c_fn_args_pfx)
837 for idx, arg_conv_info in enumerate(argument_types):
840 if arg_conv_info.c_ty != "void":
842 if arg_conv_info.c_ty != "void":
843 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
844 out_java += (arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
846 if has_out_java_struct:
849 out_java_struct += ("\t// Skipped " + method_name + "\n")
850 has_out_java_struct = False
852 meth_n = method_name[len(struct_meth) + 1:]
855 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
857 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
858 for idx, arg in enumerate(argument_types):
860 if not takes_self or idx > 1:
861 out_java_struct += (", ")
864 if arg.java_ty != "void":
865 if arg.arg_name in default_constructor_args:
866 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
868 out_java_struct += (", ")
870 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
872 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
875 if out_java_struct is not None:
876 out_java_struct += (") {\n")
877 for info in argument_types:
878 if info.arg_conv is not None:
879 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
880 if return_type_info.ret_conv is not None:
881 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
882 elif return_type_info.c_ty != "void":
883 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
886 if c_call_string is None:
887 out_c += (method_name + "(")
889 out_c += (c_call_string)
890 for idx, info in enumerate(argument_types):
891 if info.arg_conv_name is not None:
894 elif c_call_string is not None:
896 out_c += (info.arg_conv_name)
898 if return_type_info.ret_conv is not None:
899 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
902 for info in argument_types:
903 if info.arg_conv_cleanup is not None:
904 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
905 if return_type_info.ret_conv is not None:
906 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
907 elif return_type_info.c_ty != "void":
908 out_c += ("\n\treturn ret_val;")
911 if has_out_java_struct:
912 out_java_struct += ("\t\t")
913 if return_type_info.java_ty != "void":
914 out_java_struct += (return_type_info.java_ty + " ret = ")
915 out_java_struct += ("bindings." + method_name + "(")
916 for idx, info in enumerate(argument_types):
918 out_java_struct += (", ")
919 if idx == 0 and takes_self:
920 out_java_struct += ("this.ptr")
921 elif info.arg_name in default_constructor_args:
922 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
923 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
925 out_java_struct += (", ")
926 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
927 if explode_arg.from_hu_conv is not None:
929 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
931 out_java_struct += (expl_arg_name)
932 out_java_struct += (")")
933 elif info.from_hu_conv is not None:
934 out_java_struct += (info.from_hu_conv[0])
936 out_java_struct += (info.arg_name)
937 out_java_struct += (");\n")
938 if return_type_info.to_hu_conv is not None:
940 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
941 return_type_info.to_hu_conv_name) + "\n")
943 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
945 for idx, info in enumerate(argument_types):
946 if idx == 0 and takes_self:
948 elif info.arg_name in default_constructor_args:
949 for explode_arg in default_constructor_args[info.arg_name]:
950 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
951 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
952 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
953 expl_arg_name).replace(
954 "this", return_type_info.to_hu_conv_name) + ";\n")
955 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
956 if not takes_self and return_type_info.to_hu_conv_name is not None:
958 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name) + ";\n")
960 out_java_struct += ("\t\t" + info.from_hu_conv[1] + ";\n")
962 if return_type_info.to_hu_conv_name is not None:
963 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
964 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
965 out_java_struct += ("\t\treturn ret;\n")
966 out_java_struct += ("\t}\n\n")
968 return (out_java, out_c, out_java_struct)