1 from bindingstypes import *
8 def first_to_lower(string: str) -> str:
10 return first.lower() + string[1:]
12 def safe_arg_name(arg_name):
13 return "_" + arg_name if arg_name == "lock" or arg_name == "event" or arg_name == "params" else arg_name
15 def arg_name_repl(s, arg_name):
16 return s.replace(arg_name, "_" + arg_name) if arg_name == "lock" or arg_name == "event" or arg_name == "params" else s
19 def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
22 self.c_array_class_caches = set()
23 self.function_ptr_counter = 0
24 self.function_ptrs = {}
25 self.c_type_map = dict(
34 self.java_type_map = dict(
37 self.java_hu_type_map = dict(
41 self.to_hu_conv_templates = dict(
42 ptr = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }',
43 default = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }'
46 self.bindings_header = """
50 using System.Collections.Generic;
51 using System.Runtime.InteropServices;
53 namespace org { namespace ldk { namespace impl {
55 internal class bindings {
56 static List<WeakReference> js_objs = new List<WeakReference>();
57 internal class ArrayCoder : ICustomMarshaler {
59 public static ICustomMarshaler GetInstance(string pstrCookie) {
60 return new ArrayCoder();
63 public Object MarshalNativeToManaged(IntPtr pNativeData) { throw new NotImplementedException(); }
64 public IntPtr MarshalManagedToNative(Object obj) {
65 if (obj.GetType() == typeof(byte[])) {
66 byte[] inp = (byte[])obj;
67 IntPtr data = Marshal.AllocHGlobal(inp.Length + 8);
68 Marshal.WriteInt64(data, inp.Length);
69 Marshal.Copy(inp, 0, data + 8, inp.Length);
70 this.size = inp.Length + 8;
73 throw new NotImplementedException();
76 public void CleanUpNativeData(IntPtr pNativeData) {
77 Marshal.FreeHGlobal(pNativeData);
79 public void CleanUpManagedData(Object ManagedObj) { }
80 public int GetNativeDataSize() {
81 // Blindly guess based on the last allocation, no idea how else to implement this.
87 init(java.lang.Enum.class, VecOrSliceDef.class);
89 if (!get_lib_version_string().equals(version.get_ldk_java_bindings_version()))
90 throw new ArgumentException("Compiled LDK library and LDK class failes do not match");
91 // Fetching the LDK versions from C also checks that the header and binaries match
92 Console.Error.WriteLine("Loaded LDK-Java Bindings " + version.get_ldk_java_bindings_version() + " with LDK " + get_ldk_version() + " and LDK-C-Bindings " + get_ldk_c_bindings_version());
94 //static extern void init(java.lang.Class c);
95 //static native void init_class_cache();
97 self.bindings_header += self.native_meth_decl("get_lib_version_string", "string") + "();\n"
98 self.bindings_header += self.native_meth_decl("get_ldk_c_bindings_version", "string") + "();\n"
99 self.bindings_header += self.native_meth_decl("get_ldk_version", "string") + "();\n\n"
101 self.bindings_version_file = """
103 public class version {
104 public static string get_ldk_java_bindings_version() {
105 return "<git_version_ldk_garbagecollected>";
109 self.util_fn_pfx = """using org.ldk.impl;
112 using org.ldk.structs;
115 namespace org { namespace ldk { namespace util {
116 public class UtilMethods {
118 self.util_fn_sfx = "} } } }"
119 self.common_base = """using System.Collections.Generic;
120 using System.Diagnostics;
122 public class CommonBase {
123 protected internal long ptr;
124 protected internal LinkedList<object> ptrs_to = new LinkedList<object>();
125 protected CommonBase(long ptr) { Trace.Assert(ptr < 0 || ptr > 4096); this.ptr = ptr; }
129 self.txin_defn = """public class TxIn : CommonBase {
130 /** The witness in this input, in serialized form */
131 public readonly byte[] witness;
132 /** The script_sig in this input */
133 public readonly byte[] script_sig;
134 /** The transaction output's sequence number */
135 public readonly int sequence;
136 /** The txid this input is spending */
137 public readonly byte[] previous_txid;
138 /** The output index within the spent transaction of the output this input is spending */
139 public readonly int previous_vout;
141 internal TxIn(object _dummy, long ptr) : base(ptr) {
142 this.witness = bindings.TxIn_get_witness(ptr);
143 this.script_sig = bindings.TxIn_get_script_sig(ptr);
144 this.sequence = bindings.TxIn_get_sequence(ptr);
145 this.previous_txid = bindings.TxIn_get_previous_txid(ptr);
146 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
148 public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout)
149 : this(null, bindings.TxIn_new(witness, script_sig, sequence, previous_txid, previous_vout)) {}
152 if (ptr != 0) { bindings.TxIn_free(ptr); }
156 self.txout_defn = """public class TxOut : CommonBase {
157 /** The script_pubkey in this output */
158 public readonly byte[] script_pubkey;
159 /** The value, in satoshis, of this output */
160 public readonly long value;
162 internal TxOut(object _dummy, long ptr) : base(ptr) {
163 this.script_pubkey = bindings.TxOut_get_script_pubkey(ptr);
164 this.value = bindings.TxOut_get_value(ptr);
166 public TxOut(long value, byte[] script_pubkey) : this(null, bindings.TxOut_new(script_pubkey, value)) {}
169 if (ptr != 0) { bindings.TxOut_free(ptr); }
173 self.scalar_defn = """public class BigEndianScalar : CommonBase {
174 /** The bytes of the scalar value, in big endian */
175 public readonly byte[] scalar_bytes;
177 internal BigEndianScalar(object _dummy, long ptr) : base(ptr) {
178 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
180 public BigEndianScalar(byte[] scalar_bytes) : base(bindings.BigEndianScalar_new(scalar_bytes)) {
181 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
185 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
190 self.c_file_pfx = """
191 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
192 #define int64_t jlong
193 #include <lightning.h>
195 #include <stdatomic.h>
198 #define LIKELY(v) __builtin_expect(!!(v), 1)
199 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
203 self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
205 if not DEBUG or sys.platform == "darwin":
206 self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
207 #define MALLOC(a, _) malloc(a)
208 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
209 #define CHECK_ACCESS(p)
210 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
213 self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
217 self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
218 // Always run a, then assert it is true:
219 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
220 // Assert a is true or do nothing
221 #define CHECK(a) DO_ASSERT(a)
223 void __attribute__((constructor)) debug_log_version() {
224 if (check_get_ldk_version() == NULL)
225 DEBUG_PRINT("LDK version did not match the header we built against\\n");
226 if (check_get_ldk_bindings_version() == NULL)
227 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
231 if sys.platform != "darwin":
232 self.c_file_pfx += """
233 // Running a leak check across all the allocations and frees of the JDK is a mess,
234 // so instead we implement our own naive leak checker here, relying on the -wrap
235 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
236 // and free'd in Rust or C across the generated bindings shared library.
240 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
241 self.c_file_pfx = self.c_file_pfx + """
244 static pthread_mutex_t allocation_mtx;
246 void __attribute__((constructor)) init_mtx() {
247 DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
251 typedef struct allocation {
252 struct allocation* next;
254 const char* struct_name;
257 unsigned long alloc_len;
259 static allocation* allocation_ll = NULL;
261 void* __real_malloc(size_t len);
262 void* __real_calloc(size_t nmemb, size_t len);
263 static void new_allocation(void* res, const char* struct_name, size_t len) {
264 allocation* new_alloc = __real_malloc(sizeof(allocation));
265 new_alloc->ptr = res;
266 new_alloc->struct_name = struct_name;
267 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
268 new_alloc->alloc_len = len;
269 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
270 new_alloc->next = allocation_ll;
271 allocation_ll = new_alloc;
272 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
274 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
275 void* res = __real_malloc(len);
276 new_allocation(res, struct_name, lineno);
279 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
281 void __real_free(void* ptr);
282 static void alloc_freed(void* ptr) {
283 allocation* p = NULL;
284 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
285 allocation* it = allocation_ll;
286 while (it->ptr != ptr) {
287 p = it; it = it->next;
289 DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
291 int bt_len = backtrace(bt, BT_MAX);
292 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
293 DEBUG_PRINT("\\n\\n");
294 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
295 return; // addrsan should catch malloc-unknown and print more info than we have
298 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
299 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
300 DO_ASSERT(it->ptr == ptr);
303 static void FREE(void* ptr) {
304 if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
309 void* __wrap_malloc(size_t len) {
310 void* res = __real_malloc(len);
311 new_allocation(res, "malloc call", len);
314 void* __wrap_calloc(size_t nmemb, size_t len) {
315 void* res = __real_calloc(nmemb, len);
316 new_allocation(res, "calloc call", len);
319 void __wrap_free(void* ptr) {
320 if (ptr == NULL) return;
325 static void CHECK_ACCESS(const void* ptr) {
326 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
327 allocation* it = allocation_ll;
328 while (it->ptr != ptr) {
331 DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
333 int bt_len = backtrace(bt, BT_MAX);
334 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
335 DEBUG_PRINT("\\n\\n");
336 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
337 return; // addrsan should catch and print more info than we have
340 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
342 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
343 if (v.is_owned && v.inner != NULL) { \\
344 const void *p = __unmangle_inner_ptr(v.inner); \\
350 void* __real_realloc(void* ptr, size_t newlen);
351 void* __wrap_realloc(void* ptr, size_t len) {
352 if (ptr != NULL) alloc_freed(ptr);
353 void* res = __real_realloc(ptr, len);
354 new_allocation(res, "realloc call", len);
357 void __wrap_reallocarray(void* ptr, size_t new_sz) {
358 // Rust doesn't seem to use reallocarray currently
362 void __attribute__((destructor)) check_leaks() {
363 unsigned long alloc_count = 0;
364 unsigned long alloc_size = 0;
365 DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
366 DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
367 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
368 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
369 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
370 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
371 DEBUG_PRINT("\\n\\n");
373 alloc_size += a->alloc_len;
375 DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
376 DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
377 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
380 self.c_file_pfx = self.c_file_pfx + """
382 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
383 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
384 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
385 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
387 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
389 #define DECL_ARR_TYPE(ty, name) \\
390 struct name##array { \\
391 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
394 typedef struct name##array * name##Array; \\
395 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
396 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
397 arr->arr_len = arr_len; \\
401 DECL_ARR_TYPE(int64_t, int64_t);
402 DECL_ARR_TYPE(uint64_t, uint64_t);
403 DECL_ARR_TYPE(int8_t, int8_t);
404 DECL_ARR_TYPE(int16_t, int16_t);
405 DECL_ARR_TYPE(uint32_t, uint32_t);
406 DECL_ARR_TYPE(void*, ptr);
407 DECL_ARR_TYPE(char, char);
408 typedef charArray jstring;
410 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
411 charArray arr = init_charArray(len, __LINE__);
412 memcpy(arr->elems, chars, len);
415 static inline LDKStr str_ref_to_owned_c(const jstring str) {
416 char* newchars = MALLOC(str->arr_len + 1, "String chars");
417 memcpy(newchars, str->elems, str->arr_len);
418 newchars[str->arr_len] = 0;
422 .chars_is_owned = true
427 typedef bool jboolean;
429 jstring CS_LDK_get_ldk_c_bindings_version() {
430 return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
432 jstring CS_LDK_get_ldk_version() {
433 return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
437 self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
438 return "<git_version_ldk_garbagecollected>";
441 self.hu_struct_file_prefix = """using org.ldk.impl;
446 namespace org { namespace ldk { namespace structs {
449 self.hu_struct_file_suffix = "} } }\n"
450 self.c_fn_args_pfx = ""
451 self.c_fn_ty_pfx = ""
452 self.file_ext = ".cs"
453 self.ptr_c_ty = "int64_t"
454 self.ptr_native_ty = "long"
455 self.u128_native_ty = "UInt128"
456 self.usize_c_ty = "int64_t"
457 self.usize_native_ty = "long"
458 self.native_zero_ptr = "0"
459 self.unitary_enum_c_ty = "int32_t"
460 self.ptr_arr = "ptrArray"
461 self.is_arr_some_check = ("", " != NULL")
462 self.get_native_arr_len_call = ("", "->arr_len")
464 self.bindings_footer_wip = "\tstatic bindings() {\n"
465 def bindings_footer(self):
468 def native_meth_decl(self, meth_name, ret_ty_str):
469 return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
471 def c_fn_name_define_pfx(self, fn_name, have_args):
472 return " CS_LDK_" + fn_name + "("
474 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
476 def create_native_arr_call(self, arr_len, ty_info):
477 if ty_info.c_ty == "ptrArray":
478 assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and (ty_info.subty.c_ty.endswith("Array") or ty_info.subty.rust_obj == "LDKStr"))
479 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
480 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
481 if ty_info.c_ty == "int8_tArray":
482 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
483 elif ty_info.c_ty == "int16_tArray":
484 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
487 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
488 if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
491 if ty_info.c_ty == "int16_tArray":
492 byte_len = arr_len + " * 2"
493 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
495 if ty_info.c_ty == "ptrArray":
496 return "(void*) " + arr_name + "->elems"
498 return arr_name + "->elems"
499 def get_native_arr_elem(self, arr_name, idxc, ty_info):
500 assert False # Only called if above is None
501 def get_native_arr_ptr_call(self, ty_info):
502 if ty_info.subty is not None:
503 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
504 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
505 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
507 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
508 if ty_info.c_ty == "int8_tArray":
509 return "FREE(" + arr_name + ");"
511 return "FREE(" + arr_name + ")"
513 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
514 if elem_ty.java_hu_ty == "UInt5":
515 return arr_name + " != null ? InternalUtils.convUInt5Array(" + arr_name + ") : null"
516 elif elem_ty.java_hu_ty == "WitnessVersion":
517 return arr_name + " != null ? InternalUtils.convWitnessVersionArray(" + arr_name + ") : null"
519 return arr_name + " != null ? InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
521 def str_ref_to_native_call(self, var_name, str_len):
522 return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
523 def str_ref_to_c_call(self, var_name):
524 return "str_ref_to_owned_c(" + var_name + ")"
525 def str_to_hu_conv(self, var_name):
527 def str_from_hu_conv(self, var_name):
532 for fn_suffix in self.function_ptrs:
533 cret = self.function_ptrs[fn_suffix]["ret"][1]
534 cargs = self.function_ptrs[fn_suffix]["args"][1]
536 typedef {cret} (*invoker_{fn_suffix})(int obj_ptr, int fn_id{cargs});
537 static invoker_{fn_suffix} js_invoke_function_{fn_suffix};
538 int CS_LDK_register_{fn_suffix}_invoker(invoker_{fn_suffix} invoker) {{
539 js_invoke_function_{fn_suffix} = invoker;
546 def var_decl_statement(self, ty_string, var_name, statement):
547 return ty_string + " " + var_name + " = " + statement
549 def get_java_arr_len(self, arr_name):
550 return arr_name + ".Length"
551 def get_java_arr_elem(self, elem_ty, arr_name, idx):
552 return arr_name + "[" + idx + "]"
553 def constr_hu_array(self, ty_info, arr_len):
554 base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
555 conv = "new " + base_ty + "[" + arr_len + "]"
556 if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
557 # Do a bit of a dance to move any excess [] to the end
558 conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
560 def cleanup_converted_native_array(self, ty_info, arr_name):
563 def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
564 mapped_ty = arr_ty.subty
565 if arr_ty.rust_obj == "LDKU128":
566 return ("" + arr_name + ".getLEBytes()", "")
567 if fixed_len is not None:
568 return ("InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")", "")
570 def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
571 if arr_ty.rust_obj == "LDKU128":
572 return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
575 def java_arr_ty_str(self, elem_ty_str):
576 return elem_ty_str + "[]"
578 def for_n_in_range(self, n, minimum, maximum):
579 return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
580 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
581 return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
583 def get_ptr(self, var):
585 def set_null_skip_free(self, var):
586 return var + ".ptr" + " = 0;"
588 def add_ref(self, holder, referent):
589 return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
591 def fully_qualified_hu_ty_path(self, ty):
592 if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
594 if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
595 return "org.ldk.util." + ty.java_hu_ty
596 if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
597 return "org.ldk.structs." + ty.java_hu_ty
600 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
601 out_java_enum = "namespace org { namespace ldk { namespace enums {"
605 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
606 out_c += "\tswitch (ord) {\n"
608 if enum_doc_comment is not None:
609 out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
610 out_java_enum += "public enum " + struct_name + " {\n"
612 for var, var_docs in variants:
613 if var_docs is not None:
614 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
615 out_java_enum += "\t" + var + ",\n"
616 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
619 out_c += "\t\tdefault: abort();\n"
623 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
624 out_c = out_c + "\tswitch (val) {\n"
626 for var, _ in variants:
627 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
629 out_c = out_c + "\t\tdefault: abort();\n"
630 out_c = out_c + "\t}\n"
631 out_c = out_c + "}\n"
633 return (out_c, out_java_enum + "} } }\n", out_java)
635 def c_unitary_enum_to_native_call(self, ty_info):
636 return (ty_info.rust_obj + "_to_cs(", ")")
637 def native_unitary_enum_to_c_call(self, ty_info):
638 return (ty_info.rust_obj + "_from_cs(", ")")
640 def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
643 out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
644 out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
645 out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
646 for var_name in variants:
647 out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
648 out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
649 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
650 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"
651 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
652 out_c = out_c + "}\n"
655 def c_complex_enum_pass_ty(self, struct_name):
658 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
659 ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
660 for param in c_params:
661 ret = ret + ", " + param
664 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
665 out_typescript_bindings = ""
666 super_instantiator = ""
667 bindings_instantiator = ""
668 pointer_to_adder = ""
669 impl_constructor_arguments = ""
670 for var in flattened_field_var_conversions:
671 if isinstance(var, ConvInfo):
672 impl_constructor_arguments += f", {var.java_hu_ty} {var.arg_name}"
673 if var.from_hu_conv is not None:
674 bindings_instantiator += ", " + var.from_hu_conv[0]
675 if var.from_hu_conv[1] != "":
676 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
678 bindings_instantiator += ", " + first_to_lower(var.arg_name)
680 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
681 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.AddLast(" + first_to_lower(var[1]) + ");\n"
682 impl_constructor_arguments += f", {var[0].replace('LDK', '')}Interface {first_to_lower(var[1])}_impl"
684 super_constructor_statements = ""
685 trait_constructor_arguments = ""
686 for var in field_var_conversions:
687 if isinstance(var, ConvInfo):
688 trait_constructor_arguments += ", " + var.arg_name
690 super_constructor_statements += "\t\t" + var[1] + " " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
691 super_instantiator = ""
692 for suparg in var[2]:
693 if isinstance(suparg, ConvInfo):
694 super_instantiator += ", " + suparg.arg_name
696 super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
697 super_constructor_statements += super_instantiator + ");\n"
698 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
699 for suparg in var[2]:
700 if isinstance(suparg, ConvInfo):
701 trait_constructor_arguments += ", " + suparg.arg_name
703 # Blindly assume that we can just strip the first arg to build the args for the supertrait
704 super_constructor_statements += "\t\t" + suparg[1] + " " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
705 trait_constructor_arguments += ", " + suparg[1]
707 # BUILD INTERFACE METHODS
709 java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
710 java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
711 java_trait_wrapper += "\t\tinternal " + struct_name + "Impl(" + struct_name.replace("LDK", "") + "Interface arg, " + struct_name + "Holder impl_holder) { this.arg = arg; this.impl_holder = impl_holder; }\n"
712 java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
713 java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
715 for fn_line in field_function_lines:
716 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
717 fn_name = fn_line.fn_name
718 if fn_name == "lock": # reserved symbol
720 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
722 for idx, arg_conv_info in enumerate(fn_line.args_ty):
724 java_trait_wrapper += ", "
725 java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
727 java_trait_wrapper += ") {\n"
729 for arg_info in fn_line.args_ty:
730 if arg_info.to_hu_conv is not None:
731 java_trait_wrapper += "\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t").replace(arg_info.arg_name, "_" + arg_info.arg_name) + "\n"
733 if fn_line.ret_ty_info.java_ty != "void":
734 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
736 java_trait_wrapper += "\t\t\targ." + fn_name + "("
738 for idx, arg_info in enumerate(fn_line.args_ty):
740 java_trait_wrapper += ", "
741 if arg_info.to_hu_conv_name is not None:
742 java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
744 java_trait_wrapper += "_" + arg_info.arg_name
746 java_trait_wrapper += ");\n"
747 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
748 if fn_line.ret_ty_info.java_ty != "void":
749 if fn_line.ret_ty_info.from_hu_conv is not None:
750 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
751 if fn_line.ret_ty_info.from_hu_conv[1] != "":
752 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
753 java_trait_wrapper += "\t\t\treturn result;\n"
755 java_trait_wrapper += "\t\t\treturn ret;\n"
756 java_trait_wrapper += "\t\t}\n"
757 java_trait_wrapper += "\t}"
759 out_java_interface = ""
761 for fn_line in field_function_lines:
762 java_method_descriptor = ""
763 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
764 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
765 out_java_interface += "\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
767 for idx, arg_conv_info in enumerate(fn_line.args_ty):
769 out_java_interface += ", "
770 out_java_interface += f"{arg_conv_info.java_hu_ty} {safe_arg_name(arg_conv_info.arg_name)}"
771 java_method_descriptor += arg_conv_info.java_fn_ty_arg
772 out_java_interface += f");\n"
773 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
774 java_methods.append((fn_line.fn_name, java_method_descriptor))
776 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
777 out_typescript_human = f"""
778 {self.hu_struct_file_prefix}
780 /** An implementation of {struct_name.replace("LDK","")} */
781 public interface {struct_name.replace("LDK", "")}Interface {{
782 {out_java_interface}}}
785 * {formatted_trait_docs}
787 public class {struct_name.replace("LDK","")} : CommonBase {{
788 internal bindings.{struct_name} bindings_instance;
789 internal long instance_idx;
791 internal {struct_name.replace("LDK","")}(object _dummy, long ptr) : base(ptr) {{ bindings_instance = null; }}
792 ~{struct_name.replace("LDK","")}() {{
793 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
798 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
799 public static {struct_name.replace("LDK", "")} new_impl({struct_name.replace("LDK", "")}Interface arg{impl_constructor_arguments}) {{
800 {struct_name}Holder impl_holder = new {struct_name}Holder();
801 {struct_name}Impl impl = new {struct_name}Impl(arg, impl_holder);
802 {super_constructor_statements} long[] ptr_idx = bindings.{struct_name}_new(impl{bindings_instantiator});
804 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
805 impl_holder.held.instance_idx = ptr_idx[1];
806 impl_holder.held.bindings_instance = impl;
807 {pointer_to_adder} return impl_holder.held;
812 out_typescript_bindings += "\tpublic interface " + struct_name + " {\n"
814 for fn_line in field_function_lines:
815 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
816 out_typescript_bindings += f"\t\t{fn_line.ret_ty_info.java_ty} {fn_line.fn_name}("
818 for idx, arg_conv_info in enumerate(fn_line.args_ty):
820 out_typescript_bindings = out_typescript_bindings + ", "
821 out_typescript_bindings += f"{arg_conv_info.java_ty} {safe_arg_name(arg_conv_info.arg_name)}"
823 out_typescript_bindings += f");\n"
825 out_typescript_bindings += "\t}\n"
827 c_call_extra_args = ""
828 native_fn_args = "long impl_idx"
829 for var in flattened_field_var_conversions:
830 if isinstance(var, ConvInfo):
831 native_fn_args += ", " + var.java_ty + " " + var.arg_name
833 native_fn_args += ", long " + var[1]
834 out_typescript_bindings += self.native_meth_decl(struct_name + "_new", "long") + "_native(" + native_fn_args + ");\n"
835 out_typescript_bindings += f"\tpublic static long[] {struct_name}_new({struct_name} impl"
836 for var in flattened_field_var_conversions:
837 if isinstance(var, ConvInfo):
838 out_typescript_bindings += f", {var.java_ty} {var.arg_name}"
839 c_call_extra_args += f", {var.arg_name}"
841 out_typescript_bindings += f", long {var[1]}"
842 c_call_extra_args += f", {var[1]}"
845 out_typescript_bindings += f""") {{
846 long new_obj_idx = js_objs.Count;
848 for (; i < js_objs.Count; i++) {{
849 if (js_objs[i] == null || !js_objs[i].IsAlive) {{ new_obj_idx = i; break; }}
851 if (i == js_objs.Count) {{
852 js_objs.Add(new WeakReference(impl));
854 js_objs[i] = new WeakReference(impl);
856 long[] ret = new long[2];
857 ret[0] = {struct_name}_new_native(i{c_call_extra_args});
863 # Now that we've written out our java code (and created java_meths), generate C
864 out_c = "typedef struct " + struct_name + "_JCalls {\n"
865 out_c += "\tatomic_size_t refcnt;\n"
866 out_c += "\tuint32_t instance_ptr;\n"
867 for var in flattened_field_var_conversions:
868 if isinstance(var, ConvInfo):
869 # We're a regular ol' field
873 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
874 out_c = out_c + "} " + struct_name + "_JCalls;\n"
876 for fn_line in field_function_lines:
877 if fn_line.fn_name == "free":
878 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
879 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
880 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
881 out_c = out_c + "\t\tFREE(j_calls);\n"
882 out_c = out_c + "\t}\n}\n"
884 for idx, fn_line in enumerate(field_function_lines):
885 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
886 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
887 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
888 if fn_line.self_is_const:
889 out_c = out_c + "const void* this_arg"
891 out_c = out_c + "void* this_arg"
893 for idx, arg in enumerate(fn_line.args_ty):
894 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
896 out_c = out_c + ") {\n"
897 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
899 for arg_info in fn_line.args_ty:
900 if arg_info.ret_conv is not None:
901 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
902 out_c = out_c + arg_info.arg_name
903 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
905 ty_to_c = lambda jty, ty: "b" if jty == "bool" else "c" if jty == "char" else "s" if jty == "short" else "i" if jty == "int" else "l" if jty == "long" else "void" if jty == "void" else jty
907 fn_java_callback_args = ""
908 fn_c_callback_args = ""
909 fn_callback_call_args = ""
910 fn_suffix = ty_to_c(fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info) + "_"
912 for arg_info in fn_line.args_ty:
913 fn_suffix += ty_to_c(arg_info.java_ty, arg_info)
914 fn_java_callback_args += ", " + arg_info.java_ty + " " + chr(ord("a") + idx)
915 fn_c_callback_args += ", " + arg_info.c_ty + " " + chr(ord("a") + idx)
917 fn_callback_call_args += ", "
918 fn_callback_call_args += chr(ord("a") + idx)
920 if fn_line.ret_ty_info.c_ty.endswith("Array"):
921 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
922 out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
923 elif fn_line.ret_ty_info.java_ty == "void":
924 out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
925 elif fn_line.ret_ty_info.java_hu_ty == "string":
926 out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
927 elif fn_line.ret_ty_info.arg_conv is None:
928 out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
930 out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
932 if fn_suffix not in self.function_ptrs:
933 self.function_ptrs[fn_suffix] = {"args": [fn_java_callback_args, fn_c_callback_args], "ret": [fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info.c_ty]}
934 self.function_ptrs[fn_suffix][self.function_ptr_counter] = (struct_name, fn_line.fn_name, fn_callback_call_args)
935 self.function_ptr_counter += 1
937 for idx, arg_info in enumerate(fn_line.args_ty):
938 if arg_info.ret_conv is not None:
939 if arg_info.c_ty.endswith("Array"):
940 out_c += ", (int64_t)" + arg_info.ret_conv_name
942 out_c += ", " + arg_info.ret_conv_name
944 assert False # TODO: Would we need some conversion here?
945 out_c += ", (int64_t)" + arg_info.arg_name
946 out_c = out_c + ");\n"
947 if fn_line.ret_ty_info.arg_conv is not None:
948 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"
950 out_c = out_c + "}\n"
952 # Write out a clone function whether we need one or not, as we use them in moving to rust
953 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
954 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
955 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
956 for var in flattened_field_var_conversions:
957 if not isinstance(var, ConvInfo):
958 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
959 out_c = out_c + "}\n"
961 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (int64_t o"
962 for var in flattened_field_var_conversions:
963 if isinstance(var, ConvInfo):
964 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
966 out_c = out_c + ", int64_t " + var[1]
967 out_c = out_c + ") {\n"
969 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
970 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
971 out_c = out_c + "\tcalls->instance_ptr = o;\n"
973 for (fn_name, java_meth_descr) in java_meths:
974 if fn_name != "free" and fn_name != "cloned":
975 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
976 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
978 for var in flattened_field_var_conversions:
979 if isinstance(var, ConvInfo) and var.arg_conv is not None:
980 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
981 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
982 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
983 for fn_line in field_function_lines:
984 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
985 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
986 elif fn_line.fn_name == "free":
987 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
989 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
990 for var in field_var_conversions:
991 if isinstance(var, ConvInfo):
992 if var.arg_conv_name is not None:
993 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
994 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
996 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
997 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
999 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1000 for suparg in var[2]:
1001 if isinstance(suparg, ConvInfo):
1002 out_c += ", " + suparg.arg_name
1004 out_c += ", " + suparg[1]
1006 out_c = out_c + "\t};\n"
1007 for var in flattened_field_var_conversions:
1008 if not isinstance(var, ConvInfo):
1009 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1010 out_c = out_c + "\treturn ret;\n"
1011 out_c = out_c + "}\n"
1013 out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "int32_t o"
1014 for var in flattened_field_var_conversions:
1015 if isinstance(var, ConvInfo):
1016 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1018 out_c = out_c + ", int32_t " + var[1]
1019 out_c = out_c + ") {\n"
1020 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1021 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1022 for var in flattened_field_var_conversions:
1023 if isinstance(var, ConvInfo):
1024 out_c = out_c + ", " + var.arg_name
1026 out_c = out_c + ", " + var[1]
1027 out_c = out_c + ");\n"
1028 out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1029 out_c = out_c + "}\n"
1031 return (out_typescript_bindings, out_typescript_human, out_c)
1033 def trait_struct_inc_refcnt(self, ty_info):
1034 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1035 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1036 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1039 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1040 bindings_type = struct_name.replace("LDK", "")
1041 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1047 out_java_enum += (self.hu_struct_file_prefix)
1049 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1050 java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
1051 java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
1052 java_hu_class += "\t~" + java_hu_type + "() {\n"
1053 java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
1054 java_hu_class += "\t}\n\n"
1055 java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
1056 java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1057 out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
1058 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1059 out_c += "\tswitch(obj->tag) {\n"
1060 java_hu_class += "\t\tswitch (raw_ty) {\n"
1061 java_hu_subclasses = ""
1064 for var in variant_list:
1065 java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1066 java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1067 java_hu_class += f"\t\t\tcase {var_idx}: "
1068 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1069 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1071 for idx, (field_ty, field_docs) in enumerate(var.fields):
1072 if field_docs is not None:
1073 java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1074 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1075 if field_ty.to_hu_conv is not None:
1076 hu_conv_body += f"\t\t\t{field_ty.java_ty} {field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1077 hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1078 hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1080 hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1081 java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1082 java_hu_subclasses += hu_conv_body
1083 java_hu_subclasses += "\t\t}\n\t}\n"
1085 java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1086 out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1087 out_c += ("\t\tdefault: abort();\n")
1088 out_c += ("\t}\n}\n")
1090 for var in variant_list:
1091 for idx, (field_map, _) in enumerate(var.fields):
1092 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1093 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1094 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1095 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1096 if field_map.ret_conv is not None:
1097 out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
1098 if var.tuple_variant:
1099 out_c += "obj->" + camel_to_snake(var.var_name)
1101 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1102 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1103 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1105 if var.tuple_variant:
1106 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1108 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1110 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1111 out_java_enum += java_hu_class
1112 out_java_enum += java_hu_subclasses
1113 return (out_java, out_java_enum, out_c)
1115 def map_opaque_struct(self, struct_name, struct_doc_comment):
1116 out_opaque_struct_human = ""
1117 out_opaque_struct_human += self.hu_struct_file_prefix
1118 out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1119 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1120 out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1121 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1122 out_opaque_struct_human += (", IDisposable")
1123 out_opaque_struct_human += (" {\n")
1124 out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1125 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1126 out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1128 out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1129 out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1130 out_opaque_struct_human += ("\t}\n\n")
1131 return out_opaque_struct_human
1133 def map_tuple(self, struct_name):
1134 return self.map_opaque_struct(struct_name, "A Tuple")
1136 def map_result(self, struct_name, res_map, err_map):
1137 human_ty = struct_name.replace("LDKCResult", "Result")
1139 java_hu_struct += self.hu_struct_file_prefix
1140 java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1141 java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1142 java_hu_struct += "\t~" + human_ty + "() {\n"
1143 java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1144 java_hu_struct += "\t}\n\n"
1145 java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1146 java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1147 java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1148 java_hu_struct += "\t\t} else {\n"
1149 java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1150 java_hu_struct += "\t\t}\n"
1151 java_hu_struct += "\t}\n"
1153 java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1155 if res_map.java_hu_ty != "void":
1156 java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1157 java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1158 if res_map.java_hu_ty == "void":
1160 elif res_map.to_hu_conv is not None:
1161 java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1162 java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1163 java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1165 java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1166 java_hu_struct += "\t\t}\n"
1167 java_hu_struct += "\t}\n\n"
1169 java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1170 if err_map.java_hu_ty != "void":
1171 java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1172 java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1173 if err_map.java_hu_ty == "void":
1175 elif err_map.to_hu_conv is not None:
1176 java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1177 java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1178 java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1180 java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1181 java_hu_struct += "\t\t}\n"
1183 java_hu_struct += "\t}\n\n"
1184 return java_hu_struct
1186 def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1189 out_java_struct = None
1191 out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1192 out_c += (return_type_info.c_ty)
1193 if return_type_info.ret_conv is not None:
1194 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1195 have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1196 out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1198 for idx, arg_conv_info in enumerate(argument_types):
1202 if arg_conv_info.c_ty != "void":
1203 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1204 if "[]" in arg_conv_info.java_ty:
1205 out_java += "[MarshalAs(UnmanagedType.CustomMarshaler, MarshalType=\"org.ldk.impl.ArrayCoder\")] "
1206 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1208 out_java_struct = ""
1209 extra_java_struct_out = ""
1211 out_java_struct += ("\t// Skipped " + method_name + "\n")
1213 if doc_comment is not None:
1214 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1215 hu_ret_ty = return_type_info.java_hu_ty
1216 if return_type_info.nullable:
1217 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1221 out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1222 elif meth_n == "default":
1223 out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1225 out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1226 elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1227 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1229 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1230 extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1231 extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1232 extra_java_struct_out += "\t}\n"
1233 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1234 extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1235 extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1236 extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1237 extra_java_struct_out += "\t}\n"
1238 if meth_n == "lock":
1239 out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1241 out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1242 for idx, arg in enumerate(argument_types):
1244 if not takes_self or idx > 1:
1245 out_java_struct += ", "
1248 if arg.java_ty != "void":
1249 if arg.arg_name in default_constructor_args:
1250 assert not arg.nullable
1251 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1252 if explode_idx != 0:
1253 out_java_struct += (", ")
1254 out_java_struct += (
1255 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1257 ty_string = arg.java_hu_ty
1259 #ty_string += "?" - apparently mono doesn't support the nullable stuff
1261 ty_string = self.fully_qualified_hu_ty_path(arg)
1262 out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1263 out_java += (");\n")
1265 if out_java_struct is not None:
1266 out_java_struct += (") {\n")
1267 for info in argument_types:
1268 if info.arg_conv is not None:
1269 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1270 if return_type_info.ret_conv is not None:
1271 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1272 elif return_type_info.c_ty != "void":
1273 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1276 if c_call_string is None:
1277 out_c += (method_name + "(")
1279 out_c += (c_call_string)
1280 for idx, info in enumerate(argument_types):
1281 if info.arg_conv_name is not None:
1284 elif c_call_string is not None:
1286 out_c += (info.arg_conv_name)
1288 if return_type_info.ret_conv is not None:
1289 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1292 for info in argument_types:
1293 if info.arg_conv_cleanup is not None:
1294 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1295 if return_type_info.ret_conv is not None:
1296 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1297 elif return_type_info.c_ty != "void":
1298 out_c += ("\n\treturn ret_val;")
1299 out_c += ("\n}\n\n")
1302 out_java_struct += ("\t\t")
1303 if return_type_info.java_ty != "void":
1304 out_java_struct += (return_type_info.java_ty + " ret = ")
1305 out_java_struct += ("bindings." + method_name + "(")
1306 for idx, info in enumerate(argument_types):
1308 out_java_struct += (", ")
1309 if idx == 0 and takes_self:
1310 out_java_struct += ("this.ptr")
1311 elif info.arg_name in default_constructor_args:
1312 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1313 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1314 if explode_idx != 0:
1315 out_java_struct += (", ")
1316 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1317 if explode_arg.from_hu_conv is not None:
1318 out_java_struct += (
1319 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1321 out_java_struct += (expl_arg_name)
1322 out_java_struct += (")")
1323 elif info.from_hu_conv is not None:
1324 out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1326 out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1327 out_java_struct += (");\n")
1329 # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1330 # on it is operating. Unlike Java, this behavior appears to be better documented,
1332 for idx, info in enumerate(argument_types):
1333 if idx == 0 and takes_self:
1334 out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1335 elif info.arg_name in default_constructor_args:
1336 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1337 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1338 out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1339 elif info.c_ty != "void":
1340 out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1342 if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1343 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1345 if return_type_info.to_hu_conv is not None:
1347 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1348 .replace("this", return_type_info.to_hu_conv_name) + "\n")
1350 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1352 for idx, info in enumerate(argument_types):
1353 if idx == 0 and takes_self:
1355 elif info.arg_name in default_constructor_args:
1356 for explode_arg in default_constructor_args[info.arg_name]:
1357 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1358 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1359 out_java_struct += ("\t\t" +
1360 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1361 .replace(explode_arg.arg_name, expl_arg_name)
1362 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1363 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1364 if not takes_self and return_type_info.to_hu_conv_name is not None:
1365 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1366 .replace("this", return_type_info.to_hu_conv_name)
1367 .replace("\n", "\n\t\t") + ";\n")
1369 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1370 .replace("\n", "\n\t\t") + ";\n")
1372 if takes_self and not takes_self_as_ref:
1373 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1374 if return_type_info.to_hu_conv_name is not None:
1375 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1376 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1377 out_java_struct += ("\t\treturn ret;\n")
1378 out_java_struct += ("\t}\n\n")
1380 return (out_java, out_c, out_java_struct + extra_java_struct_out)
1383 with open(self.outdir + "src/org/ldk/impl/bindings.cs", "a") as bindings:
1384 for fn_suffix in self.function_ptrs:
1385 jret = self.function_ptrs[fn_suffix]["ret"][0]
1386 jargs = self.function_ptrs[fn_suffix]["args"][0]
1389 static {jret} c_callback_{fn_suffix}(int obj_ptr, int fn_id{jargs}) {{
1390 if (obj_ptr >= js_objs.Count) {{
1391 Console.Error.WriteLine("Got function call on unknown/free'd JS object in {fn_suffix}");
1392 Console.Error.Flush();
1393 Environment.Exit(42);
1395 object obj = js_objs[obj_ptr].Target;
1397 Console.Error.WriteLine("Got function call on GC'd JS object in {fn_suffix}");
1398 Console.Error.Flush();
1399 Environment.Exit(43);
1402 bindings.write("\t\tswitch (fn_id) {\n")
1403 for f in self.function_ptrs[fn_suffix]:
1404 if f != "ret" and f != "args" and f != "call":
1405 bindings.write(f"""\t\t\tcase {str(f)}:
1406 if (!(obj is {self.function_ptrs[fn_suffix][f][0]})) {{
1407 Console.Error.WriteLine("Got function call to object that wasn't a {self.function_ptrs[fn_suffix][f][0]} in {fn_suffix}");
1408 Console.Error.Flush();
1409 Environment.Exit(44);
1411 call = f"(({self.function_ptrs[fn_suffix][f][0]})obj).{self.function_ptrs[fn_suffix][f][1]}({self.function_ptrs[fn_suffix][f][2]});"
1413 bindings.write("\t\t\t\treturn " + call)
1415 bindings.write("\t\t\t\t" + call + "\n\t\t\t\treturn;")
1416 bindings.write("\n")
1418 bindings.write(f"""\t\t\tdefault:
1419 Console.Error.WriteLine("Got unknown function call with id " + fn_id + " from C in {fn_suffix}");
1420 Console.Error.Flush();
1421 Environment.Exit(45);
1422 return{" false" if jret == "bool" else " 0" if jret != "void" else ""};
1425 public delegate {jret} {fn_suffix}_callback(int obj_ptr, int fn_id{jargs});
1427 bindings.write(self.native_meth_decl(f"register_{fn_suffix}_invoker", "int") + f"({fn_suffix}_callback callee);\n")
1428 # Easiest way to get a static run is just define a variable, even if we dont care
1429 bindings.write(f"\tstatic int _run_{fn_suffix}_registration = register_{fn_suffix}_invoker(c_callback_{fn_suffix});")