Update CI references to LDK 0.0.121 branches
[ldk-java] / csharp_strings.py
1 from bindingstypes import *
2 from enum import Enum
3 import sys
4
5 class Target(Enum):
6     CSHARP = 1,
7
8 def first_to_lower(string: str) -> str:
9     first = string[0]
10     return first.lower() + string[1:]
11
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
14
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
17
18 class Consts:
19     def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
20         self.outdir = outdir
21         self.target = target
22         self.c_array_class_caches = set()
23         self.function_ptr_counter = 0
24         self.function_ptrs = {}
25         self.c_type_map = dict(
26             bool = ['bool', 'long', 'bool[]'],
27             uint8_t = ['byte', 'long', 'byte[]'],
28             uint16_t = ['short', 'long', 'short[]'],
29             uint32_t = ['int', 'long', 'int[]'],
30             uint64_t = ['long', 'long', 'long[]'],
31             int64_t = ['long', 'long', 'long[]'],
32             double = ['double', 'long', 'double[]'],
33         )
34         self.java_type_map = dict(
35             String = "long"
36         )
37         self.java_hu_type_map = dict(
38             String = "string"
39         )
40
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}); }'
44         )
45
46         self.bindings_header = """
47 using org.ldk.enums;
48 using org.ldk.impl;
49 using System;
50 using System.Collections.Generic;
51 using System.Runtime.InteropServices;
52
53 namespace org { namespace ldk { namespace impl {
54
55 internal class bindings {
56         static List<WeakReference> js_objs = new List<WeakReference>();
57
58 """
59         self.bindings_header += self.native_meth_decl("get_lib_version_string", "string") + "();\n"
60         self.bindings_header += self.native_meth_decl("get_ldk_c_bindings_version", "string") + "();\n"
61         self.bindings_header += self.native_meth_decl("get_ldk_version", "string") + "();\n\n"
62         self.bindings_header += self.native_meth_decl("allocate_buffer", "long") + "(long buflen);\n\n"
63         self.bindings_header += self.native_meth_decl("free_buffer", "void") + "(long buf);\n\n"
64
65         self.bindings_version_file = """
66
67 public class version {
68         public static string get_ldk_java_bindings_version() {
69                 return "<git_version_ldk_garbagecollected>";
70         }
71 }"""
72
73         self.util_fn_pfx = """using org.ldk.impl;
74 using org.ldk.enums;
75 using org.ldk.util;
76 using org.ldk.structs;
77 using System;
78
79 namespace org { namespace ldk { namespace util {
80 public class UtilMethods {
81 """
82         self.util_fn_sfx = "} } } }"
83         self.common_base = """using System.Collections.Generic;
84 using System.Diagnostics;
85
86 public class CommonBase {
87         protected internal long ptr;
88         protected internal LinkedList<object> ptrs_to = new LinkedList<object>();
89         protected CommonBase(long ptr) { Trace.Assert(ptr < 0 || ptr > 4096); this.ptr = ptr; }
90 }
91 """
92
93         self.txin_defn = """public class TxIn : CommonBase {
94         /** The witness in this input, in serialized form */
95         public readonly byte[] witness;
96         /** The script_sig in this input */
97         public readonly byte[] script_sig;
98         /** The transaction output's sequence number */
99         public readonly int sequence;
100         /** The txid this input is spending */
101         public readonly byte[] previous_txid;
102         /** The output index within the spent transaction of the output this input is spending */
103         public readonly int previous_vout;
104
105         internal TxIn(object _dummy, long ptr) : base(ptr) {
106                 this.witness = InternalUtils.decodeUint8Array(bindings.TxIn_get_witness(ptr));
107                 this.script_sig = InternalUtils.decodeUint8Array(bindings.TxIn_get_script_sig(ptr));
108                 this.sequence = bindings.TxIn_get_sequence(ptr);
109                 this.previous_txid = InternalUtils.decodeUint8Array(bindings.TxIn_get_previous_txid(ptr));
110                 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
111         }
112         public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout)
113         : this(null, bindings.TxIn_new(InternalUtils.encodeUint8Array(witness), InternalUtils.encodeUint8Array(script_sig), sequence, InternalUtils.encodeUint8Array(previous_txid), previous_vout)) {}
114
115         ~TxIn() {
116                 if (ptr != 0) { bindings.TxIn_free(ptr); }
117         }
118 }"""
119
120         self.txout_defn = """public class TxOut : CommonBase {
121         /** The script_pubkey in this output */
122         public readonly byte[] script_pubkey;
123         /** The value, in satoshis, of this output */
124         public readonly long value;
125
126     internal TxOut(object _dummy, long ptr) : base(ptr) {
127                 this.script_pubkey = InternalUtils.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
128                 this.value = bindings.TxOut_get_value(ptr);
129         }
130     public TxOut(long value, byte[] script_pubkey) : this(null, bindings.TxOut_new(InternalUtils.encodeUint8Array(script_pubkey), value)) {}
131
132         ~TxOut() {
133                 if (ptr != 0) { bindings.TxOut_free(ptr); }
134         }
135 }"""
136
137         self.scalar_defn = """public class BigEndianScalar : CommonBase {
138         /** The bytes of the scalar value, in big endian */
139         public readonly byte[] scalar_bytes;
140
141     internal BigEndianScalar(object _dummy, long ptr) : base(ptr) {
142                 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
143         }
144     public BigEndianScalar(byte[] scalar_bytes) : base(bindings.BigEndianScalar_new(InternalUtils.encodeUint8Array(scalar_bytes))) {
145                 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
146         }
147
148         ~BigEndianScalar() {
149                 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
150         }
151 }"""
152
153         self.witness_program_defn = """public class WitnessProgram : CommonBase {
154         /** The witness program bytes themselves */
155         public readonly byte[] program;
156         /** The witness version */
157         public readonly WitnessVersion version;
158
159         internal WitnessProgram(object _dummy, long ptr) : base(ptr) {
160                 this.program = InternalUtils.decodeUint8Array(bindings.WitnessProgram_get_program(ptr));
161                 this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
162         }
163         static private long check_args(byte[] program, WitnessVersion version) {
164                 if (program.Length < 2 || program.Length > 40) throw new ArgumentException();
165                 if (version.getVal() == 0 && program.Length != 20 && program.Length != 32) throw new ArgumentException();
166                 return InternalUtils.encodeUint8Array(program);
167         }
168         public WitnessProgram(byte[] program, WitnessVersion version) :
169                 this(null, bindings.WitnessProgram_new(version.getVal(), check_args(program, version))) {}
170
171         ~WitnessProgram() {
172                 if (ptr != 0) { bindings.WitnessProgram_free(ptr); }
173         }
174 }"""
175
176         self.c_file_pfx = """
177 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
178 #define int64_t jlong
179 #include <lightning.h>
180 #include <string.h>
181 #include <stdatomic.h>
182 #include <stdlib.h>
183
184 #define LIKELY(v) __builtin_expect(!!(v), 1)
185 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
186
187 """
188
189         self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
190
191         if not DEBUG or sys.platform == "darwin":
192             self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
193 #define MALLOC(a, _) malloc(a)
194 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
195 #define CHECK_ACCESS(p)
196 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
197 """
198         if not DEBUG:
199             self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
200 #define CHECK(a)
201 """
202         if DEBUG:
203             self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
204 // Always run a, then assert it is true:
205 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
206 // Assert a is true or do nothing
207 #define CHECK(a) DO_ASSERT(a)
208
209 void __attribute__((constructor)) debug_log_version() {
210         if (check_get_ldk_version() == NULL)
211                 DEBUG_PRINT("LDK version did not match the header we built against\\n");
212         if (check_get_ldk_bindings_version() == NULL)
213                 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
214 }
215 """
216
217             if sys.platform != "darwin":
218                 self.c_file_pfx += """
219 // Running a leak check across all the allocations and frees of the JDK is a mess,
220 // so instead we implement our own naive leak checker here, relying on the -wrap
221 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
222 // and free'd in Rust or C across the generated bindings shared library.
223 #include <threads.h>
224 """
225
226                 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
227                 self.c_file_pfx = self.c_file_pfx + """
228 #include <unistd.h>
229 #include <pthread.h>
230 static pthread_mutex_t allocation_mtx;
231
232 void __attribute__((constructor)) init_mtx() {
233         DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
234 }
235
236 #define BT_MAX 128
237 typedef struct allocation {
238         struct allocation* next;
239         void* ptr;
240         const char* struct_name;
241         void* bt[BT_MAX];
242         int bt_len;
243         unsigned long alloc_len;
244 } allocation;
245 static allocation* allocation_ll = NULL;
246
247 void* __real_malloc(size_t len);
248 void* __real_calloc(size_t nmemb, size_t len);
249 static void new_allocation(void* res, const char* struct_name, size_t len) {
250         allocation* new_alloc = __real_malloc(sizeof(allocation));
251         new_alloc->ptr = res;
252         new_alloc->struct_name = struct_name;
253         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
254         new_alloc->alloc_len = len;
255         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
256         new_alloc->next = allocation_ll;
257         allocation_ll = new_alloc;
258         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
259 }
260 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
261         void* res = __real_malloc(len);
262         new_allocation(res, struct_name, lineno);
263         return res;
264 }
265 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
266
267 void __real_free(void* ptr);
268 static void alloc_freed(void* ptr) {
269         allocation* p = NULL;
270         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
271         allocation* it = allocation_ll;
272         while (it->ptr != ptr) {
273                 p = it; it = it->next;
274                 if (it == NULL) {
275                         DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
276                         void* bt[BT_MAX];
277                         int bt_len = backtrace(bt, BT_MAX);
278                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
279                         DEBUG_PRINT("\\n\\n");
280                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
281                         return; // addrsan should catch malloc-unknown and print more info than we have
282                 }
283         }
284         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
285         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
286         DO_ASSERT(it->ptr == ptr);
287         __real_free(it);
288 }
289 static void FREE(void* ptr) {
290         if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
291         alloc_freed(ptr);
292         __real_free(ptr);
293 }
294
295 void* __wrap_malloc(size_t len) {
296         void* res = __real_malloc(len);
297         new_allocation(res, "malloc call", len);
298         return res;
299 }
300 void* __wrap_calloc(size_t nmemb, size_t len) {
301         void* res = __real_calloc(nmemb, len);
302         new_allocation(res, "calloc call", len);
303         return res;
304 }
305 void __wrap_free(void* ptr) {
306         if (ptr == NULL) return;
307         alloc_freed(ptr);
308         __real_free(ptr);
309 }
310
311 static void CHECK_ACCESS(const void* ptr) {
312         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
313         allocation* it = allocation_ll;
314         while (it->ptr != ptr) {
315                 it = it->next;
316                 if (it == NULL) {
317                         DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
318                         void* bt[BT_MAX];
319                         int bt_len = backtrace(bt, BT_MAX);
320                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
321                         DEBUG_PRINT("\\n\\n");
322                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
323                         return; // addrsan should catch and print more info than we have
324                 }
325         }
326         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
327 }
328 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
329         if (v.is_owned && v.inner != NULL) { \\
330                 const void *p = __unmangle_inner_ptr(v.inner); \\
331                 if (p != NULL) { \\
332                         CHECK_ACCESS(p); \\
333                 } \\
334         }
335
336 void* __real_realloc(void* ptr, size_t newlen);
337 void* __wrap_realloc(void* ptr, size_t len) {
338         if (ptr != NULL) alloc_freed(ptr);
339         void* res = __real_realloc(ptr, len);
340         new_allocation(res, "realloc call", len);
341         return res;
342 }
343 void __wrap_reallocarray(void* ptr, size_t new_sz) {
344         // Rust doesn't seem to use reallocarray currently
345         DO_ASSERT(false);
346 }
347
348 void __attribute__((destructor)) check_leaks() {
349         unsigned long alloc_count = 0;
350         unsigned long alloc_size = 0;
351         DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
352         DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers();\\n");
353         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
354         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
355                 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
356                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
357                 DEBUG_PRINT("\\n\\n");
358                 alloc_count++;
359                 alloc_size += a->alloc_len;
360         }
361         DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
362         DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers()\\n");
363         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
364 }
365 """
366         self.c_file_pfx = self.c_file_pfx + """
367
368 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
369 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
370 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
371 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
372
373 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
374
375 // Int types across Windows/Linux are different, so make sure we're using the right headers.
376 _Static_assert(sizeof(void*) == sizeof(uintptr_t), "stdints must be correct");
377 _Static_assert(sizeof(void*) == sizeof(intptr_t), "stdints must be correct");
378 _Static_assert(sizeof(uint64_t) == 8, "stdints must be correct");
379 _Static_assert(sizeof(int64_t) == 8, "stdints must be correct");
380 _Static_assert(sizeof(uint32_t) == 4, "stdints must be correct");
381 _Static_assert(sizeof(int32_t) == 4, "stdints must be correct");
382 _Static_assert(sizeof(uint16_t) == 2, "stdints must be correct");
383 _Static_assert(sizeof(int16_t) == 2, "stdints must be correct");
384 _Static_assert(sizeof(uint8_t) == 1, "stdints must be correct");
385 _Static_assert(sizeof(int8_t) == 1, "stdints must be correct");
386
387 #define DECL_ARR_TYPE(ty, name) \\
388         struct name##array { \\
389                 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
390                 ty elems[]; \\
391         }; \\
392         typedef struct name##array * name##Array; \\
393         static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
394                 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
395                 arr->arr_len = arr_len; \\
396                 return arr; \\
397         }
398
399 DECL_ARR_TYPE(int64_t, int64_t);
400 DECL_ARR_TYPE(uint64_t, uint64_t);
401 DECL_ARR_TYPE(int8_t, int8_t);
402 DECL_ARR_TYPE(int16_t, int16_t);
403 DECL_ARR_TYPE(uint32_t, uint32_t);
404 DECL_ARR_TYPE(void*, ptr);
405 DECL_ARR_TYPE(char, char);
406 typedef charArray jstring;
407
408 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
409         charArray arr = init_charArray(len, __LINE__);
410         memcpy(arr->elems, chars, len);
411         return arr;
412 }
413 static inline LDKStr str_ref_to_owned_c(const jstring str) {
414         char* newchars = MALLOC(str->arr_len + 1, "String chars");
415         memcpy(newchars, str->elems, str->arr_len);
416         newchars[str->arr_len] = 0;
417         LDKStr res = {
418                 .chars = newchars,
419                 .len = str->arr_len,
420                 .chars_is_owned = true
421         };
422         return res;
423 }
424
425 typedef bool jboolean;
426
427 int64_t CS_LDK_allocate_buffer(int64_t len) {
428         return (int64_t)MALLOC(len, "C#-requested buffer");
429 }
430
431 void CS_LDK_free_buffer(int64_t buf) {
432         FREE((void*)buf);
433 }
434
435 jstring CS_LDK_get_ldk_c_bindings_version() {
436         return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
437 }
438 jstring CS_LDK_get_ldk_version() {
439         return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
440 }
441 #include "version.c"
442 """
443         self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
444         return "<git_version_ldk_garbagecollected>";
445 }"""
446
447         self.hu_struct_file_prefix = """using org.ldk.impl;
448 using org.ldk.enums;
449 using org.ldk.util;
450 using System;
451
452 namespace org { namespace ldk { namespace structs {
453
454 """
455         self.hu_struct_file_suffix = "} } }\n"
456         self.c_fn_args_pfx = ""
457         self.c_fn_ty_pfx = ""
458         self.file_ext = ".cs"
459         self.ptr_c_ty = "int64_t"
460         self.ptr_native_ty = "long"
461         self.u128_native_ty = "UInt128"
462         self.usize_c_ty = "int64_t"
463         self.usize_native_ty = "long"
464         self.native_zero_ptr = "0"
465         self.unitary_enum_c_ty = "int32_t"
466         self.ptr_arr = "ptrArray"
467         self.is_arr_some_check = ("", " != NULL")
468         self.get_native_arr_len_call = ("", "->arr_len")
469
470         self.bindings_footer_wip = "\tstatic bindings() {\n"
471     def bindings_footer(self):
472         return ""
473
474     def native_meth_decl(self, meth_name, ret_ty_str):
475         return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
476
477     def c_fn_name_define_pfx(self, fn_name, have_args):
478         return " CS_LDK_" + fn_name + "("
479
480     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
481         return None
482     def create_native_arr_call(self, arr_len, ty_info):
483         if ty_info.c_ty == "ptrArray":
484             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"))
485         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
486     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
487         if ty_info.c_ty == "int8_tArray":
488             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
489         elif ty_info.c_ty == "int16_tArray":
490             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
491         else:
492             assert False
493     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
494         if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
495             if copy:
496                 byte_len = arr_len
497                 if ty_info.c_ty == "int16_tArray":
498                     byte_len = arr_len + " * 2"
499                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
500         assert not copy
501         if ty_info.c_ty == "ptrArray":
502             return "(void*) " + arr_name + "->elems"
503         else:
504             return arr_name + "->elems"
505     def get_native_arr_elem(self, arr_name, idxc, ty_info):
506         assert False # Only called if above is None
507     def get_native_arr_ptr_call(self, ty_info):
508         if ty_info.subty is not None:
509             return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
510         return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
511     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
512         return None
513     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
514         if ty_info.c_ty == "int8_tArray":
515             return "FREE(" + arr_name + ");"
516         else:
517             return "FREE(" + arr_name + ")"
518
519     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
520         if elem_ty.java_hu_ty == "UInt5":
521             return "InternalUtils.convUInt5Array(" + arr_name + ")"
522         elif elem_ty.java_hu_ty == "WitnessVersion":
523             return "InternalUtils.convWitnessVersionArray(" + arr_name + ")"
524         else:
525             return "InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ")"
526
527     def str_ref_to_native_call(self, var_name, str_len):
528         return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
529     def str_ref_to_c_call(self, var_name):
530         return "str_ref_to_owned_c(" + var_name + ")"
531     def str_to_hu_conv(self, var_name):
532         return "string " + var_name + "_conv = InternalUtils.decodeString(" + var_name + ");"
533     def str_from_hu_conv(self, var_name):
534         return ("InternalUtils.encodeString(" + var_name + ")", "")
535
536     def init_str(self):
537         ret = ""
538         for fn_suffix in self.function_ptrs:
539             cret = self.function_ptrs[fn_suffix]["ret"][1]
540             cargs = self.function_ptrs[fn_suffix]["args"][1]
541             ret += f"""
542 typedef {cret} (*invoker_{fn_suffix})(int obj_ptr, int fn_id{cargs});
543 static invoker_{fn_suffix} js_invoke_function_{fn_suffix};
544 int CS_LDK_register_{fn_suffix}_invoker(invoker_{fn_suffix} invoker) {{
545         js_invoke_function_{fn_suffix} = invoker;
546         return 0;
547 }}
548 """
549
550         return ret
551
552     def var_decl_statement(self, ty_string, var_name, statement):
553         return ty_string + " " + var_name + " = " + statement
554
555     def get_java_arr_len(self, arr_name):
556         return "InternalUtils.getArrayLength(" + arr_name + ")"
557
558     def get_java_arr_elem(self, elem_ty, arr_name, idx):
559         if elem_ty.c_ty == "int64_t" or elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t":
560             return "InternalUtils.getU64ArrayElem(" + arr_name + ", " + idx + ")"
561         elif elem_ty.rust_obj == "LDKU5":
562             return "InternalUtils.getU8ArrayElem(" + arr_name + ", " + idx + ")"
563         elif elem_ty.rust_obj == "LDKStr":
564             return "InternalUtils.getU32ArrayElem(" + arr_name + ", " + idx + ")"
565         else:
566             assert False
567
568     def constr_hu_array(self, ty_info, arr_len):
569         base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
570         conv = "new " + base_ty + "[" + arr_len + "]"
571         if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
572             # Do a bit of a dance to move any excess [] to the end
573             conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
574         return conv
575     def cleanup_converted_native_array(self, ty_info, arr_name):
576         return "bindings.free_buffer(" + arr_name + ");"
577
578     def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
579         mapped_ty = arr_ty.subty
580         inner = arr_name
581         if arr_ty.rust_obj == "LDKU128":
582             return ("InternalUtils.encodeUint8Array(" + arr_name + ".getLEBytes())", "")
583         if fixed_len is not None:
584             inner = "InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")"
585         if mapped_ty.c_ty.endswith("Array"):
586             return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
587         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
588             return ("InternalUtils.encodeUint8Array(" + inner + ")", "")
589         elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
590             return ("InternalUtils.encodeUint16Array(" + inner + ")", "")
591         elif mapped_ty.c_ty == "uint32_t":
592             return ("InternalUtils.encodeUint32Array(" + inner + ")", "")
593         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t" or mapped_ty.rust_obj == "LDKStr":
594             return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
595         else:
596             print(mapped_ty.c_ty)
597             assert False
598
599     def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
600         mapped_ty = arr_ty.subty
601         if arr_ty.rust_obj == "LDKU128":
602             return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
603         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
604             return "byte[] " + conv_name + " = InternalUtils.decodeUint8Array(" + arr_name + ");"
605         elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
606             return "short[] " + conv_name + " = InternalUtils.decodeUint16Array(" + arr_name + ");"
607         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
608             return "long[] " + conv_name + " = InternalUtils.decodeUint64Array(" + arr_name + ");"
609         else:
610             assert False
611
612     def java_arr_ty_str(self, elem_ty_str):
613         return "long"
614
615     def for_n_in_range(self, n, minimum, maximum):
616         return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
617     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
618         return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
619
620     def get_ptr(self, var):
621         return var + ".ptr"
622     def set_null_skip_free(self, var):
623         return var + ".ptr" + " = 0;"
624
625     def add_ref(self, holder, referent):
626         return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
627
628     def fully_qualified_hu_ty_path(self, ty):
629         if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
630             return ty.java_hu_ty
631         if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
632             return "org.ldk.util." + ty.java_hu_ty
633         if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
634             return "org.ldk.structs." + ty.java_hu_ty
635         return ty.java_hu_ty
636
637     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
638         out_java_enum = "namespace org { namespace ldk { namespace enums {"
639         out_java = ""
640         out_c = ""
641
642         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
643         out_c += "\tswitch (ord) {\n"
644
645         if enum_doc_comment is not None:
646             out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
647         out_java_enum += "public enum " + struct_name + " {\n"
648         ord_v = 0
649         for var, var_docs in variants:
650             if var_docs is not None:
651                 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
652             out_java_enum += "\t" + var + ",\n"
653             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
654             ord_v = ord_v + 1
655         out_java_enum += "}"
656         out_c += "\t\tdefault: abort();\n"
657         out_c += "\t}\n"
658         out_c += "}\n"
659
660         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
661         out_c = out_c + "\tswitch (val) {\n"
662         ord_v = 0
663         for var, _ in variants:
664             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
665             ord_v = ord_v + 1
666         out_c = out_c + "\t\tdefault: abort();\n"
667         out_c = out_c + "\t}\n"
668         out_c = out_c + "}\n"
669
670         return (out_c, out_java_enum + "} } }\n", out_java)
671
672     def c_unitary_enum_to_native_call(self, ty_info):
673         return (ty_info.rust_obj + "_to_cs(", ")")
674     def native_unitary_enum_to_c_call(self, ty_info):
675         return (ty_info.rust_obj + "_from_cs(", ")")
676
677     def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
678         out_c = ""
679         for var in variants:
680             out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
681             out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
682         out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
683         for var_name in variants:
684             out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
685             out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
686             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
687             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"
688             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
689         out_c = out_c + "}\n"
690         return out_c
691
692     def c_complex_enum_pass_ty(self, struct_name):
693         return "jobject"
694
695     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
696         ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
697         for param in c_params:
698             ret = ret + ", " + param
699         return ret + ")"
700
701     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
702         out_typescript_bindings = ""
703         super_instantiator = ""
704         bindings_instantiator = ""
705         pointer_to_adder = ""
706         impl_constructor_arguments = ""
707         for var in flattened_field_var_conversions:
708             if isinstance(var, ConvInfo):
709                 impl_constructor_arguments += f", {var.java_hu_ty} {var.arg_name}"
710                 if var.from_hu_conv is not None:
711                     bindings_instantiator += ", " + var.from_hu_conv[0]
712                     if var.from_hu_conv[1] != "":
713                         pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
714                 else:
715                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
716             else:
717                 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
718                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.AddLast(" + first_to_lower(var[1]) + ");\n"
719                 impl_constructor_arguments += f", {var[0].replace('LDK', '')}Interface {first_to_lower(var[1])}_impl"
720
721         super_constructor_statements = ""
722         trait_constructor_arguments = ""
723         for var in field_var_conversions:
724             if isinstance(var, ConvInfo):
725                 trait_constructor_arguments += ", " + var.arg_name
726             else:
727                 super_constructor_statements += "\t\t" + var[1] + " " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
728                 super_instantiator = ""
729                 for suparg in var[2]:
730                     if isinstance(suparg, ConvInfo):
731                         super_instantiator += ", " + suparg.arg_name
732                     else:
733                         super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
734                 super_constructor_statements += super_instantiator + ");\n"
735                 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
736                 for suparg in var[2]:
737                     if isinstance(suparg, ConvInfo):
738                         trait_constructor_arguments += ", " + suparg.arg_name
739                     else:
740                         # Blindly assume that we can just strip the first arg to build the args for the supertrait
741                         super_constructor_statements += "\t\t" + suparg[1] + " " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
742                         trait_constructor_arguments += ", " + suparg[1]
743
744         # BUILD INTERFACE METHODS
745
746         java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
747         java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
748         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"
749         java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
750         java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
751
752         for fn_line in field_function_lines:
753             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
754                 fn_name = fn_line.fn_name
755                 if fn_name == "lock": # reserved symbol
756                     fn_name = "do_lock"
757                 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
758
759                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
760                     if idx >= 1:
761                         java_trait_wrapper += ", "
762                     java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
763
764                 java_trait_wrapper += ") {\n"
765
766                 for arg_info in fn_line.args_ty:
767                     if arg_info.to_hu_conv is not None:
768                         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"
769
770                 if fn_line.ret_ty_info.java_ty != "void":
771                     java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
772                 else:
773                     java_trait_wrapper += "\t\t\targ." + fn_name + "("
774
775                 for idx, arg_info in enumerate(fn_line.args_ty):
776                     if idx != 0:
777                         java_trait_wrapper += ", "
778                     if arg_info.to_hu_conv_name is not None:
779                         java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
780                     else:
781                         java_trait_wrapper += "_" + arg_info.arg_name
782
783                 java_trait_wrapper += ");\n"
784                 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
785                 if fn_line.ret_ty_info.java_ty != "void":
786                     if fn_line.ret_ty_info.from_hu_conv is not None:
787                         java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
788                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
789                             java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
790                         java_trait_wrapper += "\t\t\treturn result;\n"
791                     else:
792                         java_trait_wrapper += "\t\t\treturn ret;\n"
793                 java_trait_wrapper += "\t\t}\n"
794         java_trait_wrapper += "\t}"
795
796         out_java_interface = ""
797         java_methods = []
798         for fn_line in field_function_lines:
799             java_method_descriptor = ""
800             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
801                 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
802                 out_java_interface += "\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
803
804                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
805                     if idx >= 1:
806                         out_java_interface += ", "
807                     out_java_interface += f"{arg_conv_info.java_hu_ty} {safe_arg_name(arg_conv_info.arg_name)}"
808                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
809                 out_java_interface += f");\n"
810                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
811                 java_methods.append((fn_line.fn_name, java_method_descriptor))
812
813         formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
814         out_typescript_human = f"""
815 {self.hu_struct_file_prefix}
816
817 /** An implementation of {struct_name.replace("LDK","")} */
818 public interface {struct_name.replace("LDK", "")}Interface {{
819 {out_java_interface}}}
820
821 /**
822  * {formatted_trait_docs}
823  */
824 public class {struct_name.replace("LDK","")} : CommonBase {{
825         internal bindings.{struct_name} bindings_instance;
826         internal long instance_idx;
827
828         internal {struct_name.replace("LDK","")}(object _dummy, long ptr) : base(ptr) {{ bindings_instance = null; }}
829         ~{struct_name.replace("LDK","")}() {{
830                 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
831         }}
832
833 {java_trait_wrapper}
834
835         /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
836         public static {struct_name.replace("LDK", "")} new_impl({struct_name.replace("LDK", "")}Interface arg{impl_constructor_arguments}) {{
837                 {struct_name}Holder impl_holder = new {struct_name}Holder();
838                 {struct_name}Impl impl = new {struct_name}Impl(arg, impl_holder);
839 {super_constructor_statements}          long[] ptr_idx = bindings.{struct_name}_new(impl{bindings_instantiator});
840
841                 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
842                 impl_holder.held.instance_idx = ptr_idx[1];
843                 impl_holder.held.bindings_instance = impl;
844 {pointer_to_adder}              return impl_holder.held;
845         }}
846
847 """
848
849         out_typescript_bindings += "\tpublic interface " + struct_name + " {\n"
850         java_meths = []
851         for fn_line in field_function_lines:
852             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
853                 out_typescript_bindings += f"\t\t{fn_line.ret_ty_info.java_ty} {fn_line.fn_name}("
854
855                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
856                     if idx >= 1:
857                         out_typescript_bindings = out_typescript_bindings + ", "
858                     out_typescript_bindings += f"{arg_conv_info.java_ty} {safe_arg_name(arg_conv_info.arg_name)}"
859
860                 out_typescript_bindings += f");\n"
861
862         out_typescript_bindings += "\t}\n"
863
864         c_call_extra_args = ""
865         native_fn_args = "long impl_idx"
866         for var in flattened_field_var_conversions:
867             if isinstance(var, ConvInfo):
868                 native_fn_args += ", " + var.java_ty + " " + var.arg_name
869             else:
870                 native_fn_args += ", long " + var[1]
871         out_typescript_bindings += self.native_meth_decl(struct_name + "_new", "long") + "_native(" + native_fn_args + ");\n"
872         out_typescript_bindings += f"\tpublic static long[] {struct_name}_new({struct_name} impl"
873         for var in flattened_field_var_conversions:
874             if isinstance(var, ConvInfo):
875                 out_typescript_bindings += f", {var.java_ty} {var.arg_name}"
876                 c_call_extra_args += f", {var.arg_name}"
877             else:
878                 out_typescript_bindings += f", long {var[1]}"
879                 c_call_extra_args += f", {var[1]}"
880
881
882         out_typescript_bindings += f""") {{
883                 long new_obj_idx = js_objs.Count;
884                 int i = 0;
885                 for (; i < js_objs.Count; i++) {{
886                         if (js_objs[i] == null || !js_objs[i].IsAlive) {{ new_obj_idx = i; break; }}
887                 }}
888                 if (i == js_objs.Count) {{
889                         js_objs.Add(new WeakReference(impl));
890                 }} else {{
891                         js_objs[i] = new WeakReference(impl);
892                 }}
893                 long[] ret = new long[2];
894                 ret[0] = {struct_name}_new_native(i{c_call_extra_args});
895                 ret[1] = i;
896                 return ret;
897         }}
898 """
899
900         # Now that we've written out our java code (and created java_meths), generate C
901         out_c = "typedef struct " + struct_name + "_JCalls {\n"
902         out_c += "\tatomic_size_t refcnt;\n"
903         out_c += "\tuint32_t instance_ptr;\n"
904         for var in flattened_field_var_conversions:
905             if isinstance(var, ConvInfo):
906                 # We're a regular ol' field
907                 pass
908             else:
909                 # We're a supertrait
910                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
911         out_c = out_c + "} " + struct_name + "_JCalls;\n"
912
913         for fn_line in field_function_lines:
914             if fn_line.fn_name == "free":
915                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
916                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
917                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
918                 out_c = out_c + "\t\tFREE(j_calls);\n"
919                 out_c = out_c + "\t}\n}\n"
920
921         for idx, fn_line in enumerate(field_function_lines):
922             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
923                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
924                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
925                 if fn_line.self_is_const:
926                     out_c = out_c + "const void* this_arg"
927                 else:
928                     out_c = out_c + "void* this_arg"
929
930                 for idx, arg in enumerate(fn_line.args_ty):
931                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
932
933                 out_c = out_c + ") {\n"
934                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
935
936                 for arg_info in fn_line.args_ty:
937                     if arg_info.ret_conv is not None:
938                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
939                         out_c = out_c + arg_info.arg_name
940                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
941
942                 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
943
944                 fn_java_callback_args = ""
945                 fn_c_callback_args = ""
946                 fn_callback_call_args = ""
947                 fn_suffix = ty_to_c(fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info) + "_"
948                 idx = 0
949                 for arg_info in fn_line.args_ty:
950                     fn_suffix += ty_to_c(arg_info.java_ty, arg_info)
951                     fn_java_callback_args += ", " + arg_info.java_ty + " " + chr(ord("a") + idx)
952                     if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
953                         fn_c_callback_args += ", int64_t " + chr(ord("a") + idx)
954                     else:
955                         fn_c_callback_args += ", " + arg_info.c_ty + " " + chr(ord("a") + idx)
956                     if idx != 0:
957                         fn_callback_call_args += ", "
958                     fn_callback_call_args += chr(ord("a") + idx)
959                     idx += 1
960                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
961                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
962                     out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
963                 elif fn_line.ret_ty_info.java_ty == "void":
964                     out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
965                 elif fn_line.ret_ty_info.java_hu_ty == "string":
966                     out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
967                 elif fn_line.ret_ty_info.arg_conv is None:
968                     out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
969                 else:
970                     out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
971
972                 if fn_suffix not in self.function_ptrs:
973                     caller_ret_c_ty = fn_line.ret_ty_info.c_ty
974                     if fn_line.ret_ty_info.c_ty.endswith("Array") or fn_line.ret_ty_info.c_ty == "jstring":
975                         caller_ret_c_ty = "int64_t"
976                     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]}
977                 self.function_ptrs[fn_suffix][self.function_ptr_counter] = (struct_name, fn_line.fn_name, fn_callback_call_args)
978                 self.function_ptr_counter += 1
979
980                 for idx, arg_info in enumerate(fn_line.args_ty):
981                     if arg_info.ret_conv is not None:
982                         if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
983                             out_c += ", (int64_t)" + arg_info.ret_conv_name
984                         else:
985                             out_c += ", " + arg_info.ret_conv_name
986                     else:
987                         assert False # TODO: Would we need some conversion here?
988                         out_c += ", (int64_t)" + arg_info.arg_name
989                 out_c = out_c + ");\n"
990                 if fn_line.ret_ty_info.arg_conv is not None:
991                     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"
992
993                 out_c = out_c + "}\n"
994
995         # Write out a clone function whether we need one or not, as we use them in moving to rust
996         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
997         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
998         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
999         for var in flattened_field_var_conversions:
1000             if not isinstance(var, ConvInfo):
1001                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
1002         out_c = out_c + "}\n"
1003
1004         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (int64_t o"
1005         for var in flattened_field_var_conversions:
1006             if isinstance(var, ConvInfo):
1007                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1008             else:
1009                 out_c = out_c + ", int64_t " + var[1]
1010         out_c = out_c + ") {\n"
1011
1012         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1013         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1014         out_c = out_c + "\tcalls->instance_ptr = o;\n"
1015
1016         for (fn_name, java_meth_descr) in java_meths:
1017             if fn_name != "free" and fn_name != "cloned":
1018                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1019                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1020
1021         for var in flattened_field_var_conversions:
1022             if isinstance(var, ConvInfo) and var.arg_conv is not None:
1023                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1024         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1025         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1026         for fn_line in field_function_lines:
1027             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1028                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1029             elif fn_line.fn_name == "free":
1030                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1031             else:
1032                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1033         for var in field_var_conversions:
1034             if isinstance(var, ConvInfo):
1035                 if var.arg_conv_name is not None:
1036                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1037                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1038                 else:
1039                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1040                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1041             else:
1042                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1043                 for suparg in var[2]:
1044                     if isinstance(suparg, ConvInfo):
1045                         out_c += ", " + suparg.arg_name
1046                     else:
1047                         out_c += ", " + suparg[1]
1048                 out_c += "),\n"
1049         out_c = out_c + "\t};\n"
1050         for var in flattened_field_var_conversions:
1051             if not isinstance(var, ConvInfo):
1052                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1053         out_c = out_c + "\treturn ret;\n"
1054         out_c = out_c + "}\n"
1055
1056         out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "int32_t o"
1057         for var in flattened_field_var_conversions:
1058             if isinstance(var, ConvInfo):
1059                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1060             else:
1061                 out_c = out_c + ", int32_t " + var[1]
1062         out_c = out_c + ") {\n"
1063         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1064         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1065         for var in flattened_field_var_conversions:
1066             if isinstance(var, ConvInfo):
1067                 out_c = out_c + ", " + var.arg_name
1068             else:
1069                 out_c = out_c + ", " + var[1]
1070         out_c = out_c + ");\n"
1071         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1072         out_c = out_c + "}\n"
1073
1074         return (out_typescript_bindings, out_typescript_human, out_c)
1075
1076     def trait_struct_inc_refcnt(self, ty_info):
1077         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1078         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1079         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1080         return base_conv
1081
1082     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1083         bindings_type = struct_name.replace("LDK", "")
1084         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1085
1086         out_java_enum = ""
1087         out_java = ""
1088         out_c = ""
1089
1090         out_java_enum += (self.hu_struct_file_prefix)
1091
1092         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1093         java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
1094         java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
1095         java_hu_class += "\t~" + java_hu_type + "() {\n"
1096         java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
1097         java_hu_class += "\t}\n\n"
1098         java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
1099         java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1100         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"
1101         out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1102         out_c += "\tswitch(obj->tag) {\n"
1103         java_hu_class += "\t\tswitch (raw_ty) {\n"
1104         java_hu_subclasses = ""
1105
1106         var_idx = 0
1107         for var in variant_list:
1108             java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1109             java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1110             java_hu_class += f"\t\t\tcase {var_idx}: "
1111             java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1112             out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1113             hu_conv_body = ""
1114             for idx, (field_ty, field_docs) in enumerate(var.fields):
1115                 if field_docs is not None:
1116                     java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1117                 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1118                 if field_ty.to_hu_conv is not None:
1119                     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"
1120                     hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1121                     hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1122                 else:
1123                     hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1124             java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1125             java_hu_subclasses += hu_conv_body
1126             java_hu_subclasses += "\t\t}\n\t}\n"
1127             var_idx += 1
1128         java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1129         out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1130         out_c += ("\t\tdefault: abort();\n")
1131         out_c += ("\t}\n}\n")
1132
1133         for var in variant_list:
1134             for idx, (field_map, _) in enumerate(var.fields):
1135                 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1136                 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"
1137                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1138                 out_c += f"\tCHECK(obj->tag == {struct_name}_{var.var_name});\n"
1139                 if field_map.ret_conv is not None:
1140                     out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
1141                     if var.tuple_variant:
1142                         out_c += "obj->" + camel_to_snake(var.var_name)
1143                     else:
1144                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1145                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1146                     out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1147                 else:
1148                     if var.tuple_variant:
1149                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1150                     else:
1151                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1152                 out_c += "}\n"
1153                 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1154         out_java_enum += java_hu_class
1155         out_java_enum += java_hu_subclasses
1156         return (out_java, out_java_enum, out_c)
1157
1158     def map_opaque_struct(self, struct_name, struct_doc_comment):
1159         out_opaque_struct_human = ""
1160         out_opaque_struct_human += self.hu_struct_file_prefix
1161         out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1162         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1163         out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1164         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1165             out_opaque_struct_human += (", IDisposable")
1166         out_opaque_struct_human += (" {\n")
1167         out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1168         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1169             out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1170         else:
1171             out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1172         out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1173         out_opaque_struct_human += ("\t}\n\n")
1174         return out_opaque_struct_human
1175
1176     def map_tuple(self, struct_name):
1177         return self.map_opaque_struct(struct_name, "A Tuple")
1178
1179     def map_result(self, struct_name, res_map, err_map):
1180         human_ty = struct_name.replace("LDKCResult", "Result")
1181         java_hu_struct = ""
1182         java_hu_struct += self.hu_struct_file_prefix
1183         java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1184         java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1185         java_hu_struct += "\t~" + human_ty + "() {\n"
1186         java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1187         java_hu_struct += "\t}\n\n"
1188         java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1189         java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1190         java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1191         java_hu_struct += "\t\t} else {\n"
1192         java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1193         java_hu_struct += "\t\t}\n"
1194         java_hu_struct += "\t}\n"
1195
1196         java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1197
1198         if res_map.java_hu_ty != "void":
1199             java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1200         java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1201         if res_map.java_hu_ty == "void":
1202             pass
1203         elif res_map.to_hu_conv is not None:
1204             java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1205             java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1206             java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1207         else:
1208             java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1209         java_hu_struct += "\t\t}\n"
1210         java_hu_struct += "\t}\n\n"
1211
1212         java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1213         if err_map.java_hu_ty != "void":
1214             java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1215         java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1216         if err_map.java_hu_ty == "void":
1217             pass
1218         elif err_map.to_hu_conv is not None:
1219             java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1220             java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1221             java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1222         else:
1223             java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1224         java_hu_struct += "\t\t}\n"
1225
1226         java_hu_struct += "\t}\n\n"
1227         return java_hu_struct
1228
1229     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):
1230         out_java = ""
1231         out_c = ""
1232         out_java_struct = None
1233
1234         out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1235         out_c += (return_type_info.c_ty)
1236         if return_type_info.ret_conv is not None:
1237             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1238         have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1239         out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1240
1241         for idx, arg_conv_info in enumerate(argument_types):
1242             if idx != 0:
1243                 out_java += (", ")
1244                 out_c += (", ")
1245             if arg_conv_info.c_ty != "void":
1246                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1247                 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1248
1249         out_java_struct = ""
1250         extra_java_struct_out = ""
1251         if not args_known:
1252             out_java_struct += ("\t// Skipped " + method_name + "\n")
1253         else:
1254             if doc_comment is not None:
1255                 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1256             hu_ret_ty = return_type_info.java_hu_ty
1257             if return_type_info.nullable:
1258                 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1259                 pass
1260             if not takes_self:
1261                 if meth_n == "new":
1262                     out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1263                 elif meth_n == "default":
1264                     out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1265                 else:
1266                     out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1267             elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1268                 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1269             else:
1270                 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1271                     extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1272                     extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1273                     extra_java_struct_out += "\t}\n"
1274                 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1275                     extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1276                     extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1277                     extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1278                     extra_java_struct_out += "\t}\n"
1279                 if meth_n == "lock":
1280                     out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1281                 else:
1282                     out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1283             for idx, arg in enumerate(argument_types):
1284                 if idx != 0:
1285                     if not takes_self or idx > 1:
1286                         out_java_struct += ", "
1287                 elif takes_self:
1288                     continue
1289                 if arg.java_ty != "void":
1290                     if arg.arg_name in default_constructor_args:
1291                         assert not arg.nullable
1292                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1293                             if explode_idx != 0:
1294                                 out_java_struct += (", ")
1295                             out_java_struct += (
1296                                 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1297                     else:
1298                         ty_string = arg.java_hu_ty
1299                         if arg.nullable:
1300                             #ty_string += "?" - apparently mono doesn't support the nullable stuff
1301                             pass
1302                         ty_string = self.fully_qualified_hu_ty_path(arg)
1303                         out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1304         out_java += (");\n")
1305         out_c += (") {\n")
1306         if out_java_struct is not None:
1307             out_java_struct += (") {\n")
1308         for info in argument_types:
1309             if info.arg_conv is not None:
1310                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1311         if return_type_info.ret_conv is not None:
1312             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1313         elif return_type_info.c_ty != "void":
1314             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1315         else:
1316             out_c += ("\t")
1317         if c_call_string is None:
1318             out_c += (method_name + "(")
1319         else:
1320             out_c += (c_call_string)
1321         for idx, info in enumerate(argument_types):
1322             if info.arg_conv_name is not None:
1323                 if idx != 0:
1324                     out_c += (", ")
1325                 elif c_call_string is not None:
1326                     continue
1327                 out_c += (info.arg_conv_name)
1328         out_c += (")")
1329         if return_type_info.ret_conv is not None:
1330             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1331         else:
1332             out_c += (";")
1333         for info in argument_types:
1334             if info.arg_conv_cleanup is not None:
1335                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1336         if return_type_info.ret_conv is not None:
1337             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1338         elif return_type_info.c_ty != "void":
1339             out_c += ("\n\treturn ret_val;")
1340         out_c += ("\n}\n\n")
1341
1342         if args_known:
1343             out_java_struct += ("\t\t")
1344             if return_type_info.java_ty != "void":
1345                 out_java_struct += (return_type_info.java_ty + " ret = ")
1346             out_java_struct += ("bindings." + method_name + "(")
1347             for idx, info in enumerate(argument_types):
1348                 if idx != 0:
1349                     out_java_struct += (", ")
1350                 if idx == 0 and takes_self:
1351                     out_java_struct += ("this.ptr")
1352                 elif info.arg_name in default_constructor_args:
1353                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1354                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1355                         if explode_idx != 0:
1356                             out_java_struct += (", ")
1357                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1358                         if explode_arg.from_hu_conv is not None:
1359                             out_java_struct += (
1360                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1361                         else:
1362                             out_java_struct += (expl_arg_name)
1363                     out_java_struct += (")")
1364                 elif info.from_hu_conv is not None:
1365                     out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1366                 else:
1367                     out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1368             out_java_struct += (");\n")
1369
1370             # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1371             # on it is operating. Unlike Java, this behavior appears to be better documented,
1372             # which is nice.
1373             for idx, info in enumerate(argument_types):
1374                 if idx == 0 and takes_self:
1375                     out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1376                 elif info.arg_name in default_constructor_args:
1377                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1378                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1379                         out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1380                 elif info.c_ty != "void":
1381                     out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1382
1383             if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1384                 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1385
1386             if return_type_info.to_hu_conv is not None:
1387                 if not takes_self:
1388                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1389                         .replace("this", return_type_info.to_hu_conv_name) + "\n")
1390                 else:
1391                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1392
1393             for idx, info in enumerate(argument_types):
1394                 if idx == 0 and takes_self:
1395                     pass
1396                 elif info.arg_name in default_constructor_args:
1397                     for explode_arg in default_constructor_args[info.arg_name]:
1398                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1399                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1400                             out_java_struct += ("\t\t" +
1401                                 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1402                                 .replace(explode_arg.arg_name, expl_arg_name)
1403                                 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1404                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1405                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1406                         out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1407                             .replace("this", return_type_info.to_hu_conv_name)
1408                             .replace("\n", "\n\t\t") + ";\n")
1409                     else:
1410                         out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1411                             .replace("\n", "\n\t\t") + ";\n")
1412
1413             if takes_self and not takes_self_as_ref:
1414                 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1415             if return_type_info.to_hu_conv_name is not None:
1416                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1417             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1418                 out_java_struct += ("\t\treturn ret;\n")
1419             out_java_struct += ("\t}\n\n")
1420
1421         return (out_java, out_c, out_java_struct + extra_java_struct_out)
1422
1423     def cleanup(self):
1424         with open(self.outdir + "src/org/ldk/impl/bindings.cs", "a") as bindings:
1425             for fn_suffix in self.function_ptrs:
1426                 jret = self.function_ptrs[fn_suffix]["ret"][0]
1427                 jargs = self.function_ptrs[fn_suffix]["args"][0]
1428
1429                 bindings.write(f"""
1430         static {jret} c_callback_{fn_suffix}(int obj_ptr, int fn_id{jargs}) {{
1431                 if (obj_ptr >= js_objs.Count) {{
1432                         Console.Error.WriteLine("Got function call on unknown/free'd JS object in {fn_suffix}");
1433                         Console.Error.Flush();
1434                         Environment.Exit(42);
1435                 }}
1436                 object obj = js_objs[obj_ptr].Target;
1437                 if (obj == null) {{
1438                         Console.Error.WriteLine("Got function call on GC'd JS object in {fn_suffix}");
1439                         Console.Error.Flush();
1440                         Environment.Exit(43);
1441                 }}
1442 """)
1443                 bindings.write("\t\tswitch (fn_id) {\n")
1444                 for f in self.function_ptrs[fn_suffix]:
1445                     if f != "ret" and f != "args" and f != "call":
1446                         bindings.write(f"""\t\t\tcase {str(f)}:
1447                                 if (!(obj is {self.function_ptrs[fn_suffix][f][0]})) {{
1448                                         Console.Error.WriteLine("Got function call to object that wasn't a {self.function_ptrs[fn_suffix][f][0]} in {fn_suffix}");
1449                                         Console.Error.Flush();
1450                                         Environment.Exit(44);
1451                                 }}\n""")
1452                         call = f"(({self.function_ptrs[fn_suffix][f][0]})obj).{self.function_ptrs[fn_suffix][f][1]}({self.function_ptrs[fn_suffix][f][2]});"
1453                         if jret != "void":
1454                             bindings.write("\t\t\t\treturn " + call)
1455                         else:
1456                             bindings.write("\t\t\t\t" + call + "\n\t\t\t\treturn;")
1457                         bindings.write("\n")
1458
1459                 bindings.write(f"""\t\t\tdefault:
1460                                 Console.Error.WriteLine("Got unknown function call with id " + fn_id + " from C in {fn_suffix}");
1461                                 Console.Error.Flush();
1462                                 Environment.Exit(45);
1463                                 return{" false" if jret == "bool" else " 0" if jret != "void" else ""};
1464                 }}
1465         }}
1466         public delegate {jret} {fn_suffix}_callback(int obj_ptr, int fn_id{jargs});
1467         static {fn_suffix}_callback {fn_suffix}_callback_inst = c_callback_{fn_suffix};
1468 """)
1469                 bindings.write(self.native_meth_decl(f"register_{fn_suffix}_invoker", "int") + f"({fn_suffix}_callback callee);\n")
1470                 # Easiest way to get a static run is just define a variable, even if we dont care
1471                 bindings.write(f"\tstatic int _run_{fn_suffix}_registration = register_{fn_suffix}_invoker({fn_suffix}_callback_inst);")
1472
1473             bindings.write("""
1474 }
1475 } } }""")