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