1 from bindingstypes import *
10 def first_to_lower(string: str) -> str:
12 return first.lower() + string[1:]
14 def safe_arg_name(arg_name):
15 return "_" + arg_name if arg_name == "lock" or arg_name == "event" or arg_name == "params" else arg_name
17 def arg_name_repl(s, arg_name):
18 return s.replace(arg_name, "_" + arg_name) if arg_name == "lock" or arg_name == "event" or arg_name == "params" else s
21 def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
24 self.c_array_class_caches = set()
25 self.function_ptr_counter = 0
26 self.function_ptrs = {}
27 self.c_type_map = dict(
28 bool = ['bool', 'long', 'bool[]'],
29 uint8_t = ['byte', 'long', 'byte[]'],
30 uint16_t = ['short', 'long', 'short[]'],
31 uint32_t = ['int', 'long', 'int[]'],
32 uint64_t = ['long', 'long', 'long[]'],
33 int64_t = ['long', 'long', 'long[]'],
34 double = ['double', 'long', 'double[]'],
36 self.java_type_map = dict(
39 self.java_hu_type_map = dict(
43 self.to_hu_conv_templates = dict(
44 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}); }',
45 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}); }'
48 self.bindings_header = """
52 using System.Collections.Generic;
53 using System.Runtime.InteropServices;
55 namespace org { namespace ldk { namespace impl {
57 internal class bindings {
58 static List<WeakReference> js_objs = new List<WeakReference>();
61 self.bindings_header += self.native_meth_decl("get_lib_version_string", "string") + "();\n"
62 self.bindings_header += self.native_meth_decl("get_ldk_c_bindings_version", "string") + "();\n"
63 self.bindings_header += self.native_meth_decl("get_ldk_version", "string") + "();\n\n"
64 self.bindings_header += self.native_meth_decl("allocate_buffer", "long") + "(long buflen);\n\n"
65 self.bindings_header += self.native_meth_decl("free_buffer", "void") + "(long buf);\n\n"
67 self.bindings_version_file = """
69 public class version {
70 public static string get_ldk_java_bindings_version() {
71 return "<git_version_ldk_garbagecollected>";
75 self.util_fn_pfx = """using org.ldk.impl;
78 using org.ldk.structs;
81 namespace org { namespace ldk { namespace util {
82 public class UtilMethods {
84 self.util_fn_sfx = "} } } }"
85 self.common_base = """using System.Collections.Generic;
86 using System.Diagnostics;
88 public class CommonBase {
89 protected internal long ptr;
90 protected internal LinkedList<object> ptrs_to = new LinkedList<object>();
91 protected CommonBase(long ptr) { Trace.Assert(ptr < 0 || ptr > 4096); this.ptr = ptr; }
95 self.txin_defn = """public class TxIn : CommonBase {
96 /** The witness in this input, in serialized form */
97 public readonly byte[] witness;
98 /** The script_sig in this input */
99 public readonly byte[] script_sig;
100 /** The transaction output's sequence number */
101 public readonly int sequence;
102 /** The txid this input is spending */
103 public readonly byte[] previous_txid;
104 /** The output index within the spent transaction of the output this input is spending */
105 public readonly int previous_vout;
107 internal TxIn(object _dummy, long ptr) : base(ptr) {
108 this.witness = InternalUtils.decodeUint8Array(bindings.TxIn_get_witness(ptr));
109 this.script_sig = InternalUtils.decodeUint8Array(bindings.TxIn_get_script_sig(ptr));
110 this.sequence = bindings.TxIn_get_sequence(ptr);
111 this.previous_txid = InternalUtils.decodeUint8Array(bindings.TxIn_get_previous_txid(ptr));
112 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
114 public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout)
115 : this(null, bindings.TxIn_new(InternalUtils.encodeUint8Array(witness), InternalUtils.encodeUint8Array(script_sig), sequence, InternalUtils.encodeUint8Array(previous_txid), previous_vout)) {}
118 if (ptr != 0) { bindings.TxIn_free(ptr); }
122 self.txout_defn = """public class TxOut : CommonBase {
123 /** The script_pubkey in this output */
124 public readonly byte[] script_pubkey;
125 /** The value, in satoshis, of this output */
126 public readonly long value;
128 internal TxOut(object _dummy, long ptr) : base(ptr) {
129 this.script_pubkey = InternalUtils.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
130 this.value = bindings.TxOut_get_value(ptr);
132 public TxOut(long value, byte[] script_pubkey) : this(null, bindings.TxOut_new(InternalUtils.encodeUint8Array(script_pubkey), value)) {}
135 if (ptr != 0) { bindings.TxOut_free(ptr); }
139 self.scalar_defn = """public class BigEndianScalar : CommonBase {
140 /** The bytes of the scalar value, in big endian */
141 public readonly byte[] scalar_bytes;
143 internal BigEndianScalar(object _dummy, long ptr) : base(ptr) {
144 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
146 public BigEndianScalar(byte[] scalar_bytes) : base(bindings.BigEndianScalar_new(InternalUtils.encodeUint8Array(scalar_bytes))) {
147 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
151 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
155 self.witness_program_defn = """public class WitnessProgram : CommonBase {
156 /** The witness program bytes themselves */
157 public readonly byte[] program;
158 /** The witness version */
159 public readonly WitnessVersion version;
161 internal WitnessProgram(object _dummy, long ptr) : base(ptr) {
162 this.program = InternalUtils.decodeUint8Array(bindings.WitnessProgram_get_program(ptr));
163 this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
165 static private long check_args(byte[] program, WitnessVersion version) {
166 if (program.Length < 2 || program.Length > 40) throw new ArgumentException();
167 if (version.getVal() == 0 && program.Length != 20 && program.Length != 32) throw new ArgumentException();
168 return InternalUtils.encodeUint8Array(program);
170 public WitnessProgram(byte[] program, WitnessVersion version) :
171 this(null, bindings.WitnessProgram_new(version.getVal(), check_args(program, version))) {}
174 if (ptr != 0) { bindings.WitnessProgram_free(ptr); }
178 self.c_file_pfx = """
179 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
180 #define int64_t jlong
181 #include <lightning.h>
183 #include <stdatomic.h>
186 #define LIKELY(v) __builtin_expect(!!(v), 1)
187 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
191 self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
193 if self.target == Target.WINDOWS:
194 self.c_file_pfx = self.c_file_pfx + """#include <heapapi.h>
195 static HANDLE process_heap = NULL;
196 static inline void* init_heap() {
197 if (UNLIKELY(process_heap == NULL)) {
198 // Assume pointer writes wont tear, which is true where we need it.
199 process_heap = GetProcessHeap();
202 static inline void* MALLOC(size_t a, const char* _) {
204 return HeapAlloc(process_heap, HEAP_ZERO_MEMORY, a);
206 #define do_MALLOC(a, b, _c) MALLOC(a, b)
207 #define FREE(p) if ((uint64_t)(p) > 4096) { init_heap(); HeapFree(process_heap, 0, p); }
208 #define CHECK_ACCESS(p)
209 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
211 elif not DEBUG or self.target != Target.LINUX:
212 self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
213 #define MALLOC(a, _) malloc(a)
214 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
215 #define CHECK_ACCESS(p)
216 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
219 self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
223 self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
224 // Always run a, then assert it is true:
225 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
226 // Assert a is true or do nothing
227 #define CHECK(a) DO_ASSERT(a)
229 void __attribute__((constructor)) debug_log_version() {
230 if (check_get_ldk_version() == NULL)
231 DEBUG_PRINT("LDK version did not match the header we built against\\n");
232 if (check_get_ldk_bindings_version() == NULL)
233 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
237 if self.target == Target.LINUX:
238 self.c_file_pfx += """
239 // Running a leak check across all the allocations and frees of the JDK is a mess,
240 // so instead we implement our own naive leak checker here, relying on the -wrap
241 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
242 // and free'd in Rust or C across the generated bindings shared library.
246 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
247 self.c_file_pfx = self.c_file_pfx + """
250 static pthread_mutex_t allocation_mtx;
252 void __attribute__((constructor)) init_mtx() {
253 DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
257 typedef struct allocation {
258 struct allocation* next;
260 const char* struct_name;
263 unsigned long alloc_len;
265 static allocation* allocation_ll = NULL;
267 void* __real_malloc(size_t len);
268 void* __real_calloc(size_t nmemb, size_t len);
269 static void new_allocation(void* res, const char* struct_name, size_t len) {
270 allocation* new_alloc = __real_malloc(sizeof(allocation));
271 new_alloc->ptr = res;
272 new_alloc->struct_name = struct_name;
273 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
274 new_alloc->alloc_len = len;
275 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
276 new_alloc->next = allocation_ll;
277 allocation_ll = new_alloc;
278 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
280 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
281 void* res = __real_malloc(len);
282 new_allocation(res, struct_name, lineno);
285 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
287 void __real_free(void* ptr);
288 static void alloc_freed(void* ptr) {
289 allocation* p = NULL;
290 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
291 allocation* it = allocation_ll;
292 while (it->ptr != ptr) {
293 p = it; it = it->next;
295 DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
297 int bt_len = backtrace(bt, BT_MAX);
298 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
299 DEBUG_PRINT("\\n\\n");
300 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
301 return; // addrsan should catch malloc-unknown and print more info than we have
304 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
305 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
306 DO_ASSERT(it->ptr == ptr);
309 static void FREE(void* ptr) {
310 if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
315 void* __wrap_malloc(size_t len) {
316 void* res = __real_malloc(len);
317 new_allocation(res, "malloc call", len);
320 void* __wrap_calloc(size_t nmemb, size_t len) {
321 void* res = __real_calloc(nmemb, len);
322 new_allocation(res, "calloc call", len);
325 void __wrap_free(void* ptr) {
326 if (ptr == NULL) return;
331 static void CHECK_ACCESS(const void* ptr) {
332 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
333 allocation* it = allocation_ll;
334 while (it->ptr != ptr) {
337 DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
339 int bt_len = backtrace(bt, BT_MAX);
340 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
341 DEBUG_PRINT("\\n\\n");
342 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
343 return; // addrsan should catch and print more info than we have
346 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
348 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
349 if (v.is_owned && v.inner != NULL) { \\
350 const void *p = __unmangle_inner_ptr(v.inner); \\
356 void* __real_realloc(void* ptr, size_t newlen);
357 void* __wrap_realloc(void* ptr, size_t len) {
358 if (ptr != NULL) alloc_freed(ptr);
359 void* res = __real_realloc(ptr, len);
360 new_allocation(res, "realloc call", len);
363 void __wrap_reallocarray(void* ptr, size_t new_sz) {
364 // Rust doesn't seem to use reallocarray currently
368 void __attribute__((destructor)) check_leaks() {
369 unsigned long alloc_count = 0;
370 unsigned long alloc_size = 0;
371 DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
372 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers();\\n");
373 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
374 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
375 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
376 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
377 DEBUG_PRINT("\\n\\n");
379 alloc_size += a->alloc_len;
381 DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
382 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers()\\n");
383 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
386 self.c_file_pfx = self.c_file_pfx + """
388 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
389 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
390 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
391 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
393 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
395 // Int types across Windows/Linux are different, so make sure we're using the right headers.
396 _Static_assert(sizeof(void*) == sizeof(uintptr_t), "stdints must be correct");
397 _Static_assert(sizeof(void*) == sizeof(intptr_t), "stdints must be correct");
398 _Static_assert(sizeof(uint64_t) == 8, "stdints must be correct");
399 _Static_assert(sizeof(int64_t) == 8, "stdints must be correct");
400 _Static_assert(sizeof(uint32_t) == 4, "stdints must be correct");
401 _Static_assert(sizeof(int32_t) == 4, "stdints must be correct");
402 _Static_assert(sizeof(uint16_t) == 2, "stdints must be correct");
403 _Static_assert(sizeof(int16_t) == 2, "stdints must be correct");
404 _Static_assert(sizeof(uint8_t) == 1, "stdints must be correct");
405 _Static_assert(sizeof(int8_t) == 1, "stdints must be correct");
407 #define DECL_ARR_TYPE(ty, name) \\
408 struct name##array { \\
409 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
412 typedef struct name##array * name##Array; \\
413 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
414 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
415 arr->arr_len = arr_len; \\
419 DECL_ARR_TYPE(int64_t, int64_t);
420 DECL_ARR_TYPE(uint64_t, uint64_t);
421 DECL_ARR_TYPE(int8_t, int8_t);
422 DECL_ARR_TYPE(int16_t, int16_t);
423 DECL_ARR_TYPE(uint32_t, uint32_t);
424 DECL_ARR_TYPE(void*, ptr);
425 DECL_ARR_TYPE(char, char);
426 typedef charArray jstring;
428 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
429 charArray arr = init_charArray(len, __LINE__);
430 memcpy(arr->elems, chars, len);
433 static inline LDKStr str_ref_to_owned_c(const jstring str) {
434 char* newchars = MALLOC(str->arr_len + 1, "String chars");
435 memcpy(newchars, str->elems, str->arr_len);
436 newchars[str->arr_len] = 0;
440 .chars_is_owned = true
445 // The C# Bool marshalling is defined as 4 bytes, but the size of bool is platform-dependent
446 typedef int32_t jboolean;
448 int64_t CS_LDK_allocate_buffer(int64_t len) {
449 return (int64_t)MALLOC(len, "C#-requested buffer");
452 void CS_LDK_free_buffer(int64_t buf) {
456 jstring CS_LDK_get_ldk_c_bindings_version() {
457 return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
459 jstring CS_LDK_get_ldk_version() {
460 return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
464 self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
465 return "<git_version_ldk_garbagecollected>";
468 self.hu_struct_file_prefix = """using org.ldk.impl;
473 namespace org { namespace ldk { namespace structs {
476 self.hu_struct_file_suffix = "} } }\n"
477 self.c_fn_args_pfx = ""
478 self.c_fn_ty_pfx = ""
479 self.file_ext = ".cs"
480 self.ptr_c_ty = "int64_t"
481 self.ptr_native_ty = "long"
482 self.u128_native_ty = "UInt128"
483 self.usize_c_ty = "int64_t"
484 self.usize_native_ty = "long"
485 self.native_zero_ptr = "0"
486 self.unitary_enum_c_ty = "int32_t"
487 self.ptr_arr = "ptrArray"
488 self.is_arr_some_check = ("", " != NULL")
489 self.get_native_arr_len_call = ("", "->arr_len")
491 self.bindings_footer_wip = "\tstatic bindings() {\n"
492 def bindings_footer(self):
495 def native_meth_decl(self, meth_name, ret_ty_str):
496 return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
498 def c_fn_name_define_pfx(self, fn_name, have_args):
499 return " CS_LDK_" + fn_name + "("
501 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
503 def create_native_arr_call(self, arr_len, ty_info):
504 if ty_info.c_ty == "ptrArray":
505 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"))
506 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
507 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
508 if ty_info.c_ty == "int8_tArray":
509 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
510 elif ty_info.c_ty == "int16_tArray":
511 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
514 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
515 if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
518 if ty_info.c_ty == "int16_tArray":
519 byte_len = arr_len + " * 2"
520 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
522 if ty_info.c_ty == "ptrArray":
523 return "(void*) " + arr_name + "->elems"
525 return arr_name + "->elems"
526 def get_native_arr_elem(self, arr_name, idxc, ty_info):
527 assert False # Only called if above is None
528 def get_native_arr_ptr_call(self, ty_info):
529 if ty_info.subty is not None:
530 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
531 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
532 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
534 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
535 if ty_info.c_ty == "int8_tArray":
536 return "FREE(" + arr_name + ");"
538 return "FREE(" + arr_name + ")"
540 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
541 if elem_ty.java_hu_ty == "UInt5":
542 return "InternalUtils.convUInt5Array(" + arr_name + ")"
543 elif elem_ty.java_hu_ty == "WitnessVersion":
544 return "InternalUtils.convWitnessVersionArray(" + arr_name + ")"
546 return "InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ")"
548 def str_ref_to_native_call(self, var_name, str_len):
549 return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
550 def str_ref_to_c_call(self, var_name):
551 return "str_ref_to_owned_c(" + var_name + ")"
552 def str_to_hu_conv(self, var_name):
553 return "string " + var_name + "_conv = InternalUtils.decodeString(" + var_name + ");"
554 def str_from_hu_conv(self, var_name):
555 return ("InternalUtils.encodeString(" + var_name + ")", "")
559 for fn_suffix in self.function_ptrs:
560 cret = self.function_ptrs[fn_suffix]["ret"][1]
561 cargs = self.function_ptrs[fn_suffix]["args"][1]
563 typedef {cret} (*invoker_{fn_suffix})(int obj_ptr, int fn_id{cargs});
564 static invoker_{fn_suffix} js_invoke_function_{fn_suffix};
565 int CS_LDK_register_{fn_suffix}_invoker(invoker_{fn_suffix} invoker) {{
566 js_invoke_function_{fn_suffix} = invoker;
573 def var_decl_statement(self, ty_string, var_name, statement):
574 return ty_string + " " + var_name + " = " + statement
576 def get_java_arr_len(self, arr_name):
577 return "InternalUtils.getArrayLength(" + arr_name + ")"
579 def get_java_arr_elem(self, elem_ty, arr_name, idx):
580 if elem_ty.c_ty == "int64_t" or elem_ty.c_ty == "uint64_t":
581 return "InternalUtils.getU64ArrayElem(" + arr_name + ", " + idx + ")"
582 elif elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t" or elem_ty.rust_obj == "LDKStr":
583 return "InternalUtils.getU64ArrayElem(" + arr_name + ", " + idx + ")"
584 elif elem_ty.rust_obj == "LDKU5":
585 return "InternalUtils.getU8ArrayElem(" + arr_name + ", " + idx + ")"
589 def constr_hu_array(self, ty_info, arr_len):
590 base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
591 conv = "new " + base_ty + "[" + arr_len + "]"
592 if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
593 # Do a bit of a dance to move any excess [] to the end
594 conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
596 def cleanup_converted_native_array(self, ty_info, arr_name):
597 return "bindings.free_buffer(" + arr_name + ");"
599 def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
600 mapped_ty = arr_ty.subty
602 if arr_ty.rust_obj == "LDKU128":
603 return ("InternalUtils.encodeUint8Array(" + arr_name + ".getLEBytes())", "")
604 if fixed_len is not None:
605 inner = "InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")"
606 if mapped_ty.c_ty.endswith("Array"):
607 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
608 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
609 return ("InternalUtils.encodeUint8Array(" + inner + ")", "")
610 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
611 return ("InternalUtils.encodeUint16Array(" + inner + ")", "")
612 elif mapped_ty.c_ty == "uint32_t":
613 return ("InternalUtils.encodeUint32Array(" + inner + ")", "")
614 elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t" or mapped_ty.rust_obj == "LDKStr":
615 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
617 print(mapped_ty.c_ty)
620 def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
621 mapped_ty = arr_ty.subty
622 if arr_ty.rust_obj == "LDKU128":
623 return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
624 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
625 return "byte[] " + conv_name + " = InternalUtils.decodeUint8Array(" + arr_name + ");"
626 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
627 return "short[] " + conv_name + " = InternalUtils.decodeUint16Array(" + arr_name + ");"
628 elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
629 return "long[] " + conv_name + " = InternalUtils.decodeUint64Array(" + arr_name + ");"
633 def java_arr_ty_str(self, elem_ty_str):
636 def for_n_in_range(self, n, minimum, maximum):
637 return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
638 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
639 return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
641 def get_ptr(self, var):
643 def set_null_skip_free(self, var):
644 return var + ".ptr" + " = 0;"
646 def add_ref(self, holder, referent):
647 return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
649 def fully_qualified_hu_ty_path(self, ty):
650 if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
652 if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
653 return "org.ldk.util." + ty.java_hu_ty
654 if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
655 return "org.ldk.structs." + ty.java_hu_ty
658 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
659 out_java_enum = "namespace org { namespace ldk { namespace enums {"
663 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
664 out_c += "\tswitch (ord) {\n"
666 if enum_doc_comment is not None:
667 out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
668 out_java_enum += "public enum " + struct_name + " {\n"
670 for var, var_docs in variants:
671 if var_docs is not None:
672 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
673 out_java_enum += "\t" + var + ",\n"
674 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
677 out_c += "\t\tdefault: abort();\n"
681 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
682 out_c = out_c + "\tswitch (val) {\n"
684 for var, _ in variants:
685 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
687 out_c = out_c + "\t\tdefault: abort();\n"
688 out_c = out_c + "\t}\n"
689 out_c = out_c + "}\n"
691 return (out_c, out_java_enum + "} } }\n", out_java)
693 def c_unitary_enum_to_native_call(self, ty_info):
694 return (ty_info.rust_obj + "_to_cs(", ")")
695 def native_unitary_enum_to_c_call(self, ty_info):
696 return (ty_info.rust_obj + "_from_cs(", ")")
698 def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
701 out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
702 out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
703 out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
704 for var_name in variants:
705 out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
706 out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
707 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
708 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"
709 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
710 out_c = out_c + "}\n"
713 def c_complex_enum_pass_ty(self, struct_name):
716 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
717 ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
718 for param in c_params:
719 ret = ret + ", " + param
722 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
723 out_typescript_bindings = ""
724 super_instantiator = ""
725 bindings_instantiator = ""
726 pointer_to_adder = ""
727 impl_constructor_arguments = ""
728 for var in flattened_field_var_conversions:
729 if isinstance(var, ConvInfo):
730 impl_constructor_arguments += f", {var.java_hu_ty} {var.arg_name}"
731 if var.from_hu_conv is not None:
732 bindings_instantiator += ", " + var.from_hu_conv[0]
733 if var.from_hu_conv[1] != "":
734 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
736 bindings_instantiator += ", " + first_to_lower(var.arg_name)
738 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
739 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.AddLast(" + first_to_lower(var[1]) + ");\n"
740 impl_constructor_arguments += f", {var[0].replace('LDK', '')}Interface {first_to_lower(var[1])}_impl"
742 super_constructor_statements = ""
743 trait_constructor_arguments = ""
744 for var in field_var_conversions:
745 if isinstance(var, ConvInfo):
746 trait_constructor_arguments += ", " + var.arg_name
748 super_constructor_statements += "\t\t" + var[1] + " " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
749 super_instantiator = ""
750 for suparg in var[2]:
751 if isinstance(suparg, ConvInfo):
752 super_instantiator += ", " + suparg.arg_name
754 super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
755 super_constructor_statements += super_instantiator + ");\n"
756 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
757 for suparg in var[2]:
758 if isinstance(suparg, ConvInfo):
759 trait_constructor_arguments += ", " + suparg.arg_name
761 # Blindly assume that we can just strip the first arg to build the args for the supertrait
762 super_constructor_statements += "\t\t" + suparg[1] + " " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
763 trait_constructor_arguments += ", " + suparg[1]
765 # BUILD INTERFACE METHODS
767 java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
768 java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
769 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"
770 java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
771 java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
773 for fn_line in field_function_lines:
774 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
775 fn_name = fn_line.fn_name
776 if fn_name == "lock": # reserved symbol
778 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
780 for idx, arg_conv_info in enumerate(fn_line.args_ty):
782 java_trait_wrapper += ", "
783 java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
785 java_trait_wrapper += ") {\n"
787 for arg_info in fn_line.args_ty:
788 if arg_info.to_hu_conv is not None:
789 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"
791 if fn_line.ret_ty_info.java_ty != "void":
792 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
794 java_trait_wrapper += "\t\t\targ." + fn_name + "("
796 for idx, arg_info in enumerate(fn_line.args_ty):
798 java_trait_wrapper += ", "
799 if arg_info.to_hu_conv_name is not None:
800 java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
802 java_trait_wrapper += "_" + arg_info.arg_name
804 java_trait_wrapper += ");\n"
805 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
806 if fn_line.ret_ty_info.java_ty != "void":
807 if fn_line.ret_ty_info.from_hu_conv is not None:
808 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
809 if fn_line.ret_ty_info.from_hu_conv[1] != "":
810 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
811 java_trait_wrapper += "\t\t\treturn result;\n"
813 java_trait_wrapper += "\t\t\treturn ret;\n"
814 java_trait_wrapper += "\t\t}\n"
815 java_trait_wrapper += "\t}"
817 out_java_interface = ""
819 for fn_line in field_function_lines:
820 java_method_descriptor = ""
821 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
822 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
823 out_java_interface += "\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
825 for idx, arg_conv_info in enumerate(fn_line.args_ty):
827 out_java_interface += ", "
828 out_java_interface += f"{arg_conv_info.java_hu_ty} {safe_arg_name(arg_conv_info.arg_name)}"
829 java_method_descriptor += arg_conv_info.java_fn_ty_arg
830 out_java_interface += f");\n"
831 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
832 java_methods.append((fn_line.fn_name, java_method_descriptor))
834 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
835 out_typescript_human = f"""
836 {self.hu_struct_file_prefix}
838 /** An implementation of {struct_name.replace("LDK","")} */
839 public interface {struct_name.replace("LDK", "")}Interface {{
840 {out_java_interface}}}
843 * {formatted_trait_docs}
845 public class {struct_name.replace("LDK","")} : CommonBase {{
846 internal bindings.{struct_name} bindings_instance;
847 internal long instance_idx;
849 internal {struct_name.replace("LDK","")}(object _dummy, long ptr) : base(ptr) {{ bindings_instance = null; }}
850 ~{struct_name.replace("LDK","")}() {{
851 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
856 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
857 public static {struct_name.replace("LDK", "")} new_impl({struct_name.replace("LDK", "")}Interface arg{impl_constructor_arguments}) {{
858 {struct_name}Holder impl_holder = new {struct_name}Holder();
859 {struct_name}Impl impl = new {struct_name}Impl(arg, impl_holder);
860 {super_constructor_statements} long[] ptr_idx = bindings.{struct_name}_new(impl{bindings_instantiator});
862 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
863 impl_holder.held.instance_idx = ptr_idx[1];
864 impl_holder.held.bindings_instance = impl;
865 {pointer_to_adder} return impl_holder.held;
870 out_typescript_bindings += "\tpublic interface " + struct_name + " {\n"
872 for fn_line in field_function_lines:
873 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
874 out_typescript_bindings += f"\t\t{fn_line.ret_ty_info.java_ty} {fn_line.fn_name}("
876 for idx, arg_conv_info in enumerate(fn_line.args_ty):
878 out_typescript_bindings = out_typescript_bindings + ", "
879 out_typescript_bindings += f"{arg_conv_info.java_ty} {safe_arg_name(arg_conv_info.arg_name)}"
881 out_typescript_bindings += f");\n"
883 out_typescript_bindings += "\t}\n"
885 c_call_extra_args = ""
886 native_fn_args = "long impl_idx"
887 for var in flattened_field_var_conversions:
888 if isinstance(var, ConvInfo):
889 native_fn_args += ", " + var.java_ty + " " + var.arg_name
891 native_fn_args += ", long " + var[1]
892 out_typescript_bindings += self.native_meth_decl(struct_name + "_new", "long") + "_native(" + native_fn_args + ");\n"
893 out_typescript_bindings += f"\tpublic static long[] {struct_name}_new({struct_name} impl"
894 for var in flattened_field_var_conversions:
895 if isinstance(var, ConvInfo):
896 out_typescript_bindings += f", {var.java_ty} {var.arg_name}"
897 c_call_extra_args += f", {var.arg_name}"
899 out_typescript_bindings += f", long {var[1]}"
900 c_call_extra_args += f", {var[1]}"
903 out_typescript_bindings += f""") {{
904 long new_obj_idx = js_objs.Count;
906 for (; i < js_objs.Count; i++) {{
907 if (js_objs[i] == null || !js_objs[i].IsAlive) {{ new_obj_idx = i; break; }}
909 if (i == js_objs.Count) {{
910 js_objs.Add(new WeakReference(impl));
912 js_objs[i] = new WeakReference(impl);
914 long[] ret = new long[2];
915 ret[0] = {struct_name}_new_native(i{c_call_extra_args});
921 # Now that we've written out our java code (and created java_meths), generate C
922 out_c = "typedef struct " + struct_name + "_JCalls {\n"
923 out_c += "\tatomic_size_t refcnt;\n"
924 out_c += "\tuint32_t instance_ptr;\n"
925 for var in flattened_field_var_conversions:
926 if isinstance(var, ConvInfo):
927 # We're a regular ol' field
931 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
932 out_c = out_c + "} " + struct_name + "_JCalls;\n"
934 for fn_line in field_function_lines:
935 if fn_line.fn_name == "free":
936 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
937 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
938 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
939 out_c = out_c + "\t\tFREE(j_calls);\n"
940 out_c = out_c + "\t}\n}\n"
942 for idx, fn_line in enumerate(field_function_lines):
943 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
944 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
945 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
946 if fn_line.self_is_const:
947 out_c = out_c + "const void* this_arg"
949 out_c = out_c + "void* this_arg"
951 for idx, arg in enumerate(fn_line.args_ty):
952 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
954 out_c = out_c + ") {\n"
955 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
957 for arg_info in fn_line.args_ty:
958 if arg_info.ret_conv is not None:
959 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
960 out_c = out_c + arg_info.arg_name
961 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
963 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
965 fn_java_callback_args = ""
966 fn_c_callback_args = ""
967 fn_callback_call_args = ""
968 fn_suffix = ty_to_c(fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info) + "_"
970 for arg_info in fn_line.args_ty:
971 fn_suffix += ty_to_c(arg_info.java_ty, arg_info)
972 fn_java_callback_args += ", " + arg_info.java_ty + " " + chr(ord("a") + idx)
973 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
974 fn_c_callback_args += ", int64_t " + chr(ord("a") + idx)
976 fn_c_callback_args += ", " + arg_info.c_ty + " " + chr(ord("a") + idx)
978 fn_callback_call_args += ", "
979 fn_callback_call_args += chr(ord("a") + idx)
981 if fn_line.ret_ty_info.c_ty.endswith("Array"):
982 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
983 out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
984 elif fn_line.ret_ty_info.java_ty == "void":
985 out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
986 elif fn_line.ret_ty_info.java_hu_ty == "string":
987 out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
988 elif fn_line.ret_ty_info.arg_conv is None:
989 out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
991 out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
993 if fn_suffix not in self.function_ptrs:
994 caller_ret_c_ty = fn_line.ret_ty_info.c_ty
995 if fn_line.ret_ty_info.c_ty.endswith("Array") or fn_line.ret_ty_info.c_ty == "jstring":
996 caller_ret_c_ty = "int64_t"
997 self.function_ptrs[fn_suffix] = {"args": [fn_java_callback_args, fn_c_callback_args], "ret": [fn_line.ret_ty_info.java_ty, caller_ret_c_ty]}
998 self.function_ptrs[fn_suffix][self.function_ptr_counter] = (struct_name, fn_line.fn_name, fn_callback_call_args)
999 self.function_ptr_counter += 1
1001 for idx, arg_info in enumerate(fn_line.args_ty):
1002 if arg_info.ret_conv is not None:
1003 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
1004 out_c += ", (int64_t)" + arg_info.ret_conv_name
1006 out_c += ", " + arg_info.ret_conv_name
1008 assert False # TODO: Would we need some conversion here?
1009 out_c += ", (int64_t)" + arg_info.arg_name
1010 out_c = out_c + ");\n"
1011 if fn_line.ret_ty_info.arg_conv is not None:
1012 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"
1014 out_c = out_c + "}\n"
1016 # Write out a clone function whether we need one or not, as we use them in moving to rust
1017 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1018 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1019 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1020 for var in flattened_field_var_conversions:
1021 if not isinstance(var, ConvInfo):
1022 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
1023 out_c = out_c + "}\n"
1025 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (int64_t o"
1026 for var in flattened_field_var_conversions:
1027 if isinstance(var, ConvInfo):
1028 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1030 out_c = out_c + ", int64_t " + var[1]
1031 out_c = out_c + ") {\n"
1033 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1034 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1035 out_c = out_c + "\tcalls->instance_ptr = o;\n"
1037 for (fn_name, java_meth_descr) in java_meths:
1038 if fn_name != "free" and fn_name != "cloned":
1039 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1040 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1042 for var in flattened_field_var_conversions:
1043 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1044 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1045 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1046 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1047 for fn_line in field_function_lines:
1048 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1049 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1050 elif fn_line.fn_name == "free":
1051 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1053 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1054 for var in field_var_conversions:
1055 if isinstance(var, ConvInfo):
1056 if var.arg_conv_name is not None:
1057 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1058 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1060 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1061 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1063 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1064 for suparg in var[2]:
1065 if isinstance(suparg, ConvInfo):
1066 out_c += ", " + suparg.arg_name
1068 out_c += ", " + suparg[1]
1070 out_c = out_c + "\t};\n"
1071 for var in flattened_field_var_conversions:
1072 if not isinstance(var, ConvInfo):
1073 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1074 out_c = out_c + "\treturn ret;\n"
1075 out_c = out_c + "}\n"
1077 out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "int32_t o"
1078 for var in flattened_field_var_conversions:
1079 if isinstance(var, ConvInfo):
1080 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1082 out_c = out_c + ", int32_t " + var[1]
1083 out_c = out_c + ") {\n"
1084 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1085 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1086 for var in flattened_field_var_conversions:
1087 if isinstance(var, ConvInfo):
1088 out_c = out_c + ", " + var.arg_name
1090 out_c = out_c + ", " + var[1]
1091 out_c = out_c + ");\n"
1092 out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1093 out_c = out_c + "}\n"
1095 return (out_typescript_bindings, out_typescript_human, out_c)
1097 def trait_struct_inc_refcnt(self, ty_info):
1098 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1099 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1100 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1103 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1104 bindings_type = struct_name.replace("LDK", "")
1105 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1111 out_java_enum += (self.hu_struct_file_prefix)
1113 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1114 java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
1115 java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
1116 java_hu_class += "\t~" + java_hu_type + "() {\n"
1117 java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
1118 java_hu_class += "\t}\n\n"
1119 java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
1120 java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1121 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"
1122 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1123 out_c += "\tswitch(obj->tag) {\n"
1124 java_hu_class += "\t\tswitch (raw_ty) {\n"
1125 java_hu_subclasses = ""
1128 for var in variant_list:
1129 java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1130 java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1131 java_hu_class += f"\t\t\tcase {var_idx}: "
1132 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1133 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1135 for idx, (field_ty, field_docs) in enumerate(var.fields):
1136 if field_docs is not None:
1137 java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1138 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1139 if field_ty.to_hu_conv is not None:
1140 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"
1141 hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1142 hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1144 hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1145 java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1146 java_hu_subclasses += hu_conv_body
1147 java_hu_subclasses += "\t\t}\n\t}\n"
1149 java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1150 out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1151 out_c += ("\t\tdefault: abort();\n")
1152 out_c += ("\t}\n}\n")
1154 for var in variant_list:
1155 for idx, (field_map, _) in enumerate(var.fields):
1156 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1157 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"
1158 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1159 out_c += f"\tCHECK(obj->tag == {struct_name}_{var.var_name});\n"
1160 if field_map.ret_conv is not None:
1161 out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
1162 if var.tuple_variant:
1163 out_c += "obj->" + camel_to_snake(var.var_name)
1165 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1166 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1167 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1169 if var.tuple_variant:
1170 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1172 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1174 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1175 out_java_enum += java_hu_class
1176 out_java_enum += java_hu_subclasses
1177 return (out_java, out_java_enum, out_c)
1179 def map_opaque_struct(self, struct_name, struct_doc_comment):
1180 out_opaque_struct_human = ""
1181 out_opaque_struct_human += self.hu_struct_file_prefix
1182 out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1183 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDKC4Tuple", "FourTuple").replace("LDK", "")
1184 out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1185 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1186 out_opaque_struct_human += (", IDisposable")
1187 out_opaque_struct_human += (" {\n")
1188 out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1189 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1190 out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1192 out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1193 out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1194 out_opaque_struct_human += ("\t}\n\n")
1195 return out_opaque_struct_human
1197 def map_tuple(self, struct_name):
1198 return self.map_opaque_struct(struct_name, "A Tuple")
1200 def map_result(self, struct_name, res_map, err_map):
1201 human_ty = struct_name.replace("LDKCResult", "Result")
1203 java_hu_struct += self.hu_struct_file_prefix
1204 java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1205 java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1206 java_hu_struct += "\t~" + human_ty + "() {\n"
1207 java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1208 java_hu_struct += "\t}\n\n"
1209 java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1210 java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1211 java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1212 java_hu_struct += "\t\t} else {\n"
1213 java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1214 java_hu_struct += "\t\t}\n"
1215 java_hu_struct += "\t}\n"
1217 java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1219 if res_map.java_hu_ty != "void":
1220 java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1221 java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1222 if res_map.java_hu_ty == "void":
1224 elif res_map.to_hu_conv is not None:
1225 java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1226 java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1227 java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1229 java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1230 java_hu_struct += "\t\t}\n"
1231 java_hu_struct += "\t}\n\n"
1233 java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1234 if err_map.java_hu_ty != "void":
1235 java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1236 java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1237 if err_map.java_hu_ty == "void":
1239 elif err_map.to_hu_conv is not None:
1240 java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1241 java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1242 java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1244 java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1245 java_hu_struct += "\t\t}\n"
1247 java_hu_struct += "\t}\n\n"
1248 return java_hu_struct
1250 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):
1253 out_java_struct = None
1255 out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1256 out_c += (return_type_info.c_ty)
1257 if return_type_info.ret_conv is not None:
1258 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1259 have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1260 out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1262 for idx, arg_conv_info in enumerate(argument_types):
1266 if arg_conv_info.c_ty != "void":
1267 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1268 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1270 out_java_struct = ""
1271 extra_java_struct_out = ""
1273 out_java_struct += ("\t// Skipped " + method_name + "\n")
1275 if doc_comment is not None:
1276 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1277 hu_ret_ty = return_type_info.java_hu_ty
1278 if return_type_info.nullable:
1279 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1283 out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1284 elif meth_n == "default":
1285 out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1287 out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1288 elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1289 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1291 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1292 extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1293 extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1294 extra_java_struct_out += "\t}\n"
1295 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1296 extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1297 extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1298 extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1299 extra_java_struct_out += "\t}\n"
1300 if meth_n == "lock":
1301 out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1303 out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1304 for idx, arg in enumerate(argument_types):
1306 if not takes_self or idx > 1:
1307 out_java_struct += ", "
1310 if arg.java_ty != "void":
1311 if arg.arg_name in default_constructor_args:
1312 assert not arg.nullable
1313 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1314 if explode_idx != 0:
1315 out_java_struct += (", ")
1316 out_java_struct += (
1317 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1319 ty_string = arg.java_hu_ty
1321 #ty_string += "?" - apparently mono doesn't support the nullable stuff
1323 ty_string = self.fully_qualified_hu_ty_path(arg)
1324 out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1325 out_java += (");\n")
1327 if out_java_struct is not None:
1328 out_java_struct += (") {\n")
1329 for info in argument_types:
1330 if info.arg_conv is not None:
1331 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1332 if return_type_info.ret_conv is not None:
1333 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1334 elif return_type_info.c_ty != "void":
1335 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1338 if c_call_string is None:
1339 out_c += (method_name + "(")
1341 out_c += (c_call_string)
1342 for idx, info in enumerate(argument_types):
1343 if info.arg_conv_name is not None:
1346 elif c_call_string is not None:
1348 out_c += (info.arg_conv_name)
1350 if return_type_info.ret_conv is not None:
1351 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1354 for info in argument_types:
1355 if info.arg_conv_cleanup is not None:
1356 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1357 if return_type_info.ret_conv is not None:
1358 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1359 elif return_type_info.c_ty != "void":
1360 out_c += ("\n\treturn ret_val;")
1361 out_c += ("\n}\n\n")
1364 out_java_struct += ("\t\t")
1365 if return_type_info.java_ty != "void":
1366 out_java_struct += (return_type_info.java_ty + " ret = ")
1367 out_java_struct += ("bindings." + method_name + "(")
1368 for idx, info in enumerate(argument_types):
1370 out_java_struct += (", ")
1371 if idx == 0 and takes_self:
1372 out_java_struct += ("this.ptr")
1373 elif info.arg_name in default_constructor_args:
1374 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1375 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1376 if explode_idx != 0:
1377 out_java_struct += (", ")
1378 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1379 if explode_arg.from_hu_conv is not None:
1380 out_java_struct += (
1381 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1383 out_java_struct += (expl_arg_name)
1384 out_java_struct += (")")
1385 elif info.from_hu_conv is not None:
1386 out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1388 out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1389 out_java_struct += (");\n")
1391 # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1392 # on it is operating. Unlike Java, this behavior appears to be better documented,
1394 for idx, info in enumerate(argument_types):
1395 if idx == 0 and takes_self:
1396 out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1397 elif info.arg_name in default_constructor_args:
1398 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1399 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1400 out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1401 elif info.c_ty != "void":
1402 out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1404 if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1405 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1407 if return_type_info.to_hu_conv is not None:
1409 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1410 .replace("this", return_type_info.to_hu_conv_name) + "\n")
1412 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1414 for idx, info in enumerate(argument_types):
1415 if idx == 0 and takes_self:
1417 elif info.arg_name in default_constructor_args:
1418 for explode_arg in default_constructor_args[info.arg_name]:
1419 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1420 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1421 out_java_struct += ("\t\t" +
1422 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1423 .replace(explode_arg.arg_name, expl_arg_name)
1424 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1425 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1426 if not takes_self and return_type_info.to_hu_conv_name is not None:
1427 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1428 .replace("this", return_type_info.to_hu_conv_name)
1429 .replace("\n", "\n\t\t") + ";\n")
1431 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1432 .replace("\n", "\n\t\t") + ";\n")
1434 if takes_self and not takes_self_as_ref:
1435 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1436 if return_type_info.to_hu_conv_name is not None:
1437 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1438 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1439 out_java_struct += ("\t\treturn ret;\n")
1440 out_java_struct += ("\t}\n\n")
1442 return (out_java, out_c, out_java_struct + extra_java_struct_out)
1445 with open(self.outdir + "src/org/ldk/impl/bindings.cs", "a") as bindings:
1446 for fn_suffix in self.function_ptrs:
1447 jret = self.function_ptrs[fn_suffix]["ret"][0]
1448 jargs = self.function_ptrs[fn_suffix]["args"][0]
1451 static {jret} c_callback_{fn_suffix}(int obj_ptr, int fn_id{jargs}) {{
1452 if (obj_ptr >= js_objs.Count) {{
1453 Console.Error.WriteLine("Got function call on unknown/free'd JS object in {fn_suffix}");
1454 Console.Error.Flush();
1455 Environment.Exit(42);
1457 object obj = js_objs[obj_ptr].Target;
1459 Console.Error.WriteLine("Got function call on GC'd JS object in {fn_suffix}");
1460 Console.Error.Flush();
1461 Environment.Exit(43);
1464 bindings.write("\t\tswitch (fn_id) {\n")
1465 for f in self.function_ptrs[fn_suffix]:
1466 if f != "ret" and f != "args" and f != "call":
1467 bindings.write(f"""\t\t\tcase {str(f)}:
1468 if (!(obj is {self.function_ptrs[fn_suffix][f][0]})) {{
1469 Console.Error.WriteLine("Got function call to object that wasn't a {self.function_ptrs[fn_suffix][f][0]} in {fn_suffix}");
1470 Console.Error.Flush();
1471 Environment.Exit(44);
1473 call = f"(({self.function_ptrs[fn_suffix][f][0]})obj).{self.function_ptrs[fn_suffix][f][1]}({self.function_ptrs[fn_suffix][f][2]});"
1475 bindings.write("\t\t\t\treturn " + call)
1477 bindings.write("\t\t\t\t" + call + "\n\t\t\t\treturn;")
1478 bindings.write("\n")
1480 bindings.write(f"""\t\t\tdefault:
1481 Console.Error.WriteLine("Got unknown function call with id " + fn_id + " from C in {fn_suffix}");
1482 Console.Error.Flush();
1483 Environment.Exit(45);
1484 return{" false" if jret == "bool" else " 0" if jret != "void" else ""};
1487 public delegate {jret} {fn_suffix}_callback(int obj_ptr, int fn_id{jargs});
1488 static {fn_suffix}_callback {fn_suffix}_callback_inst = c_callback_{fn_suffix};
1490 bindings.write(self.native_meth_decl(f"register_{fn_suffix}_invoker", "int") + f"({fn_suffix}_callback callee);\n")
1491 # Easiest way to get a static run is just define a variable, even if we dont care
1492 bindings.write(f"\tstatic int _run_{fn_suffix}_registration = register_{fn_suffix}_invoker({fn_suffix}_callback_inst);")