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