- is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
- if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
- dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
- map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(arg_conv->" + fn_line.group(2) + ")(arg_conv->this_arg")
-
- out_c.write("""#include \"org_ldk_impl_bindings.h\"
-#include <rust_types.h>
-#include <lightning.h>
-#include <string.h>
-#include <stdatomic.h>
-""")
-
- if sys.argv[4] == "false":
- out_c.write("#define MALLOC(a, _) malloc(a)\n")
- out_c.write("#define FREE free\n")
- out_c.write("#define DO_ASSERT(a) (void)(a)\n")
- else:
- out_c.write("""#include <assert.h>
-#define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
-
-#include <threads.h>
-static mtx_t allocation_mtx;
-
-void __attribute__((constructor)) init_mtx() {
- DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
-}
-
-typedef struct allocation {
- struct allocation* next;
- void* ptr;
- const char* struct_name;
-} allocation;
-static allocation* allocation_ll = NULL;
-
-void* MALLOC(size_t len, const char* struct_name) {
- void* res = malloc(len);
- allocation* new_alloc = malloc(sizeof(allocation));
- new_alloc->ptr = res;
- new_alloc->struct_name = struct_name;
- DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
- new_alloc->next = allocation_ll;
- allocation_ll = new_alloc;
- DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
- return res;
-}
-
-void FREE(void* ptr) {
- allocation* p = NULL;
- DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
- allocation* it = allocation_ll;
- while (it->ptr != ptr) { p = it; it = it->next; }
- if (p) { p->next = it->next; } else { allocation_ll = it->next; }
- DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
- DO_ASSERT(it->ptr == ptr);
- free(it);
- free(ptr);
-}
-
-void __attribute__((destructor)) check_leaks() {
- for (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr); }
- DO_ASSERT(allocation_ll == NULL);
-}
-""")
- out_java.write("""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);
- }
- static native void init(java.lang.Class c, java.lang.Class slicedef);
-
- 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[] get_u8_slice_bytes(long slice_ptr);
- public static native long bytes_to_u8_vec(byte[] bytes);
- public static native long vec_slice_len(long vec);
- public static native long new_empty_slice_vec();
-
-""")
- out_c.write("""
-jmethodID ordinal_meth = NULL;
-jmethodID slicedef_meth = NULL;
-jclass slicedef_cls = NULL;
-JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
- ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
- DO_ASSERT(ordinal_meth != NULL);
- slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
- DO_ASSERT(slicedef_meth != NULL);
- slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
- DO_ASSERT(slicedef_cls != NULL);
-}
-
-JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
- return *((bool*)ptr);
-}
-JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
- return *((long*)ptr);
-}
-JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
- FREE((void*)ptr);
-}
-JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
- LDKu8slice *slice = (LDKu8slice*)slice_ptr;
- jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
- (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
- return ret_arr;
-}
-JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
- LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
- vec->datalen = (*_env)->GetArrayLength(_env, bytes);
- vec->data = (uint8_t*)malloc(vec->datalen); // May be freed by rust, so don't track allocation
- (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
- return (long)vec;
-}
-JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
- // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
- _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
- _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
- _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
- _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
- LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
- return (long)vec->datalen;
-}
-JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
- // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
- _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
- _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
- _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
- _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
- LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
- vec->data = NULL;
- vec->datalen = 0;
- return (long)vec;
-}
-
-// We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
-_Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
-_Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
-_Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
-
-""")
-
- # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
- out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
- out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
- out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
- out_c.write("\treturn (long)key;\n") # TODO: rm me
- out_c.write("}\n") # TODO: rm me
-
- in_block_comment = False
+ is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
+ if fn_line.group(3) != "free" and fn_line.group(3) != "eq" and not is_log:
+ dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
+ map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(3) + ")(this_arg_conv->this_arg", fn_docs)
+ for idx, var_line in enumerate(field_var_lines):
+ if var_line.group(1) not in trait_structs:
+ write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
+ write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
+ write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
+ write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
+ write_c("}\n")
+ dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
+ map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, struct_name + "_set_get_" + var_line.group(2) + "(this_arg_conv", fn_docs)
+
+ def map_result(struct_name, res_ty, err_ty):
+ result_types.add(struct_name)
+ human_ty = struct_name.replace("LDKCResult", "Result")
+ with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
+ out_java_struct.write(consts.hu_struct_file_prefix)
+ out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
+ out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
+ out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
+ out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
+ out_java_struct.write("\t}\n\n")
+ out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
+ out_java_struct.write("\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n")
+ out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
+ out_java_struct.write("\t\t} else {\n")
+ out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
+ out_java_struct.write("\t\t}\n")
+ out_java_struct.write("\t}\n")
+
+ res_map = type_mapping_generator.map_type(res_ty + " res", True, None, False, True)
+ err_map = type_mapping_generator.map_type(err_ty + " err", True, None, False, True)
+ can_clone = True
+ if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
+ can_clone = False
+ if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
+ can_clone = False
+
+ create_getter(struct_name, res_ty, "ok", ("*", "->contents.result"), ("", "->result_ok"))
+ create_getter(struct_name, err_ty, "err", ("*", "->contents.err"), ("!", "->result_ok"))
+
+ out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
+
+ if res_map.java_hu_ty != "void":
+ out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
+ out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
+ out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
+ if res_map.java_hu_ty == "void":
+ pass
+ elif res_map.to_hu_conv is not None:
+ out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n")
+ out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
+ out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
+ else:
+ out_java_struct.write("\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n")
+ out_java_struct.write("\t\t}\n")
+ out_java_struct.write("\t}\n\n")
+
+ out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
+ if err_map.java_hu_ty != "void":
+ out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
+ out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
+ out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
+ if err_map.java_hu_ty == "void":
+ pass
+ elif err_map.to_hu_conv is not None:
+ out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n")
+ out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
+ out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
+ else:
+ out_java_struct.write("\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n")
+ out_java_struct.write("\t\t}\n")
+
+ out_java_struct.write("\t}\n\n")
+
+ def create_getter(struct_name, field_decl, field_name, accessor, check_sfx):
+ field_ty = java_c_types(field_decl + " " + field_name, None)
+ ptr_fn_defn = field_decl + " *" + struct_name.replace("LDK", "") + "_get_" + field_name + "(" + struct_name + " *NONNULL_PTR owner)"
+ owned_fn_defn = field_decl + " " + struct_name.replace("LDK", "") + "_get_" + field_name + "(" + struct_name + " *NONNULL_PTR owner)"
+
+ holds_ref = False
+ if field_ty.rust_obj is not None and field_ty.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
+ fn_defn = owned_fn_defn
+ write_c("static inline " + fn_defn + "{\n")
+ if check_sfx is not None:
+ write_c("CHECK(" + check_sfx[0] + "owner" + check_sfx[1] + ");\n")
+ write_c("\treturn " + field_ty.rust_obj.replace("LDK", "") + "_clone(&" + accessor[0] + "owner" + accessor[1] + ");\n")
+ elif field_ty.arr_len is not None or field_ty.is_native_primitive or field_ty.rust_obj in unitary_enums:
+ fn_defn = owned_fn_defn
+ write_c("static inline " + fn_defn + "{\n")
+ if check_sfx is not None:
+ write_c("CHECK(" + check_sfx[0] + "owner" + check_sfx[1] + ");\n")
+ write_c("\treturn " + accessor[0] + "owner" + accessor[1] + ";\n")
+ else:
+ fn_defn = ptr_fn_defn
+ write_c("static inline " + fn_defn + "{\n")
+ if check_sfx is not None:
+ write_c("CHECK(" + check_sfx[0] + "owner" + check_sfx[1] + ");\n")
+ write_c("\treturn &" + accessor[0] + "owner" + accessor[1] + ";\n")
+ holds_ref = True
+ write_c("}\n")
+ dummy_line = fn_defn + ";\n"
+ map_fn_with_ref_option(dummy_line, reg_fn_regex.match(dummy_line), None, None, "", holds_ref)
+
+ def map_tuple(struct_name, field_lines):
+ human_ty = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple")
+ with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
+ out_java_struct.write(consts.map_tuple(struct_name))
+ ty_list = []
+ for idx, (line, _) in enumerate(field_lines):
+ if idx != 0 and idx < len(field_lines) - 2:
+ ty_list.append(java_c_types(line.strip(';'), None))
+ tuple_types[struct_name] = (ty_list, struct_name)
+
+ # Map virtual getter functions
+ for idx, (line, _) in enumerate(field_lines):
+ if idx != 0 and idx < len(field_lines) - 2:
+ field_name = chr(ord('a') + idx - 1)
+ assert line.endswith(" " + field_name + ";")
+ create_getter(struct_name, line[:-3].strip(), field_name, ("", "->" + field_name), None)
+
+ out_java.write(consts.bindings_header)
+ with open(f"{sys.argv[2]}/version{consts.file_ext}", "w") as out_java_version:
+ out_java_version.write(consts.bindings_version_file.replace('<git_version_ldk_garbagecollected>', local_git_version))
+
+ with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
+ out_java_struct.write(consts.common_base)
+
+ block_comment = None
+ last_block_comment = None