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