[TS] Handle nullable arrays and objects in more cases
[ldk-java] / typescript_strings.py
1 from bindingstypes import ConvInfo
2 from enum import Enum
3
4 def first_to_lower(string: str) -> str:
5     first = string[0]
6     return first.lower() + string[1:]
7
8
9 class Target(Enum):
10     NODEJS = 1,
11     BROWSER = 2
12
13 class Consts:
14     def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
15         self.outdir = outdir
16         self.struct_file_suffixes = {}
17         self.function_ptr_counter = 0
18         self.function_ptrs = {}
19         self.c_type_map = dict(
20             uint8_t = ['number', 'number', 'Uint8Array'],
21             uint16_t = ['number', 'number', 'Uint16Array'],
22             uint32_t = ['number', 'number', 'Uint32Array'],
23             uint64_t = ['bigint', 'bigint', 'BigUint64Array'],
24         )
25         self.java_type_map = dict(
26             String = "number"
27         )
28         self.java_hu_type_map = dict(
29             String = "string"
30         )
31
32         self.to_hu_conv_templates = dict(
33             ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34             default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
35         )
36
37         self.bindings_header = """
38 import * as version from './version.mjs';
39 import { UInt5, WitnessVersion } from './structs/CommonBase.mjs';
40
41 const imports: any = {};
42 imports.env = {};
43
44 var js_objs: Array<WeakRef<object>> = [];
45 var js_invoke: Function;
46 var getRandomValues: Function;
47
48 imports.wasi_snapshot_preview1 = {
49         "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number, bytes_written_ptr: number) => {
50                 // This should generally only be used to print panic messages
51                 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
52                 var bytes_written = 0;
53                 for (var i = 0; i < iovec_array_len; i++) {
54                         const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
55                         console.log("[fd " + fd + "]: " + String.fromCharCode(...bytes_view));
56                         bytes_written += ptr_len_view[i*2+1];
57                 }
58                 const written_view = new Uint32Array(wasm.memory.buffer, bytes_written_ptr, 1);
59                 written_view[0] = bytes_written;
60                 return 0;
61         },
62         "fd_close": (_fd: number) => {
63                 // This is not generally called, but may be referenced in debug builds
64                 console.log("wasi_snapshot_preview1:fd_close");
65                 return 58; // Not Supported
66         },
67         "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
68                 // This is not generally called, but may be referenced in debug builds
69                 console.log("wasi_snapshot_preview1:fd_seek");
70                 return 58; // Not Supported
71         },
72         "random_get": (buf_ptr: number, buf_len: number) => {
73                 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
74                 getRandomValues(buf);
75                 return 0;
76         },
77         "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
78                 // This is called before fd_write to format + print panic messages
79                 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
80                 out_count_view[0] = 0;
81                 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
82                 out_len_view[0] = 0;
83                 return 0;
84         },
85         "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
86                 // This is called before fd_write to format + print panic messages,
87                 // but only if we have variables in environ_sizes_get, so shouldn't ever actually happen!
88                 console.log("wasi_snapshot_preview1:environ_get");
89                 return 58; // Note supported - we said there were 0 environment entries!
90         },
91         "proc_exit" : () => {
92                 console.log("wasi_snapshot_preview1:proc_exit");
93         },
94 };
95
96 var wasm: any = null;
97 let isWasmInitialized: boolean = false;
98
99 async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
100         if (typeof crypto === "undefined") {
101                 var crypto_import = (await import('crypto')).webcrypto;
102                 getRandomValues = crypto_import.getRandomValues.bind(crypto_import);
103         } else {
104                 getRandomValues = crypto.getRandomValues.bind(crypto);
105         }
106
107         wasm = wasmInstance.exports;
108         if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
109                 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
110         }
111
112         if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
113                 throw new Error(\"Compiled LDK library and LDK class files do not match\");
114         // Fetching the LDK versions from C also checks that the header and binaries match
115         const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
116         const ldk_ver: number = wasm.TS_get_ldk_version();
117         if (c_bindings_ver == 0)
118                 throw new Error(\"LDK version did not match the header we built against\");
119         if (ldk_ver == 0)
120                 throw new Error(\"LDK C bindings version did not match the header we built against\");
121         const c_bindings_version: string = decodeString(c_bindings_ver)
122         const ldk_version: string = decodeString(ldk_ver);
123         console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
124
125         isWasmInitialized = true;
126 }
127
128 const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu",
129         "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu"];
130
131 /* @internal */
132 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
133         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
134         const { instance: wasmInstance } = await WebAssembly.instantiate(wasmBinary, imports);
135         await finishInitializeWasm(wasmInstance);
136 }
137
138 /* @internal */
139 export async function initializeWasmFetch(uri: string) {
140         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
141         const stream = fetch(uri);
142         const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
143         await finishInitializeWasm(wasmInstance);
144 }"""
145
146         self.bindings_header += """
147 // WASM CODEC
148
149 /* @internal */
150 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
151         const arr = new Uint8Array(inputArray.length);
152         for (var i = 0; i < inputArray.length; i++) {
153                 arr[i] = inputArray[i].getVal();
154         }
155         return arr;
156 }
157
158 /* @internal */
159 export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
160         const arr = new Uint8Array(inputArray.length);
161         for (var i = 0; i < inputArray.length; i++) {
162                 arr[i] = inputArray[i].getVal();
163         }
164         return arr;
165 }
166
167
168
169 /* @internal */
170 export function encodeUint8Array (inputArray: Uint8Array|null): number {
171         if (inputArray == null) return 0;
172         const cArrayPointer = wasm.TS_malloc(inputArray.length + 8);
173         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
174         arrayLengthView[0] = BigInt(inputArray.length);
175         const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
176         arrayMemoryView.set(inputArray);
177         return cArrayPointer;
178 }
179 /* @internal */
180 export function encodeUint32Array (inputArray: Uint32Array|Array<number>|null): number {
181         if (inputArray == null) return 0;
182         const cArrayPointer = wasm.TS_malloc((inputArray.length + 2) * 4);
183         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
184         arrayLengthView[0] = BigInt(inputArray.length);
185         const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
186         arrayMemoryView.set(inputArray);
187         return cArrayPointer;
188 }
189 /* @internal */
190 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>|null): number {
191         if (inputArray == null) return 0;
192         const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 8);
193         const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, inputArray.length + 1);
194         arrayMemoryView[0] = BigInt(inputArray.length);
195         arrayMemoryView.set(inputArray, 1);
196         return cArrayPointer;
197 }
198
199 /* @internal */
200 export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array {
201         if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
202         return arr;
203 }
204
205 /* @internal */
206 export function getArrayLength(arrayPointer: number): number {
207         const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
208         const len = arraySizeViewer[0];
209         if (len >= (2n ** 32n)) throw new Error("Bogus Array Size");
210         return Number(len % (2n ** 32n));
211 }
212 /* @internal */
213 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
214         const arraySize = getArrayLength(arrayPointer);
215         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
216         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
217         // will free the underlying memory when it becomes unreachable instead of copying here.
218         // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
219         const actualArray = actualArrayViewer.slice(0, arraySize);
220         if (free) {
221                 wasm.TS_free(arrayPointer);
222         }
223         return actualArray;
224 }
225 const decodeUint32Array = (arrayPointer: number, free = true) => {
226         const arraySize = getArrayLength(arrayPointer);
227         const actualArrayViewer = new Uint32Array(
228                 wasm.memory.buffer, // value
229                 arrayPointer + 8, // offset (ignoring length bytes)
230                 arraySize // uint32 count
231         );
232         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
233         // will free the underlying memory when it becomes unreachable instead of copying here.
234         const actualArray = actualArrayViewer.slice(0, arraySize);
235         if (free) {
236                 wasm.TS_free(arrayPointer);
237         }
238         return actualArray;
239 }
240 /* @internal */
241 export function decodeUint64Array (arrayPointer: number, free = true): bigint[] {
242         const arraySize = getArrayLength(arrayPointer);
243         const actualArrayViewer = new BigUint64Array(
244                 wasm.memory.buffer, // value
245                 arrayPointer + 8, // offset (ignoring length bytes)
246                 arraySize // uint32 count
247         );
248         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
249         // will free the underlying memory when it becomes unreachable instead of copying here.
250         const actualArray = new Array(arraySize);
251         for (var i = 0; i < arraySize; i++) actualArray[i] = actualArrayViewer[i];
252         if (free) {
253                 wasm.TS_free(arrayPointer);
254         }
255         return actualArray;
256 }
257
258 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
259
260 /* @internal */
261 export function getU64ArrayElem(arrayPointer: number, idx: number): bigint {
262         const actualArrayViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
263         return actualArrayViewer[idx];
264 }
265
266 /* @internal */
267 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
268         const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
269         return actualArrayViewer[idx];
270 }
271
272 /* @internal */
273 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
274         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
275         return actualArrayViewer[idx];
276 }
277
278
279 /* @internal */
280 export function encodeString(str: string): number {
281         const charArray = new TextEncoder().encode(str);
282         return encodeUint8Array(charArray);
283 }
284
285 /* @internal */
286 export function decodeString(stringPointer: number, free = true): string {
287         const arraySize = getArrayLength(stringPointer);
288         const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 8, arraySize);
289         const result = new TextDecoder("utf-8").decode(memoryView);
290
291         if (free) {
292                 wasm.TS_free(stringPointer);
293         }
294
295         return result;
296 }
297 """
298         if DEBUG:
299             self.bindings_header += """
300 /* @internal */
301 export function getRemainingAllocationCount(): number {
302         return wasm.TS_allocs_remaining();
303 }
304 /* @internal */
305 export function debugPrintRemainingAllocs() {
306         wasm.TS_print_leaks();
307 }
308 """
309         else:
310             self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
311             self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
312
313         with open(outdir + "/index.mts", 'a') as index:
314             index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
315 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
316 export async function initializeWasmWebFetch(uri: string) {
317         await initializeWasmFetch(uri);
318 }
319 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
320 export async function initializeWasmFromBinary(bin: Uint8Array) {
321         await initializeWasmFromUint8Array(bin);
322 }
323
324 """)
325
326         self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
327         return "<git_version_ldk_garbagecollected>";
328 }"""
329
330         self.bindings_footer = ""
331
332         self.common_base = """
333 function freer(f: () => void) { f() }
334 const finalizer = new FinalizationRegistry(freer);
335 function get_freeer(ptr: bigint, free_fn: (ptr: bigint) => void) {
336         return () => {
337                 free_fn(ptr);
338         }
339 }
340
341 export class CommonBase {
342         protected ptr: bigint;
343         protected ptrs_to: object[] = [];
344         protected constructor(ptr: bigint, free_fn: (ptr: bigint) => void) {
345                 this.ptr = ptr;
346                 if (ptr != 0n){
347                         finalizer.register(this, get_freeer(ptr, free_fn), this);
348                 }
349         }
350         // In Java, protected means "any subclass can access fields on any other subclass'"
351         // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
352         // To work around this, we add accessors for other instances' protected fields here.
353         protected static add_ref_from(holder: CommonBase|null, referent: object|null) {
354                 if (holder !== null && referent !== null) { holder.ptrs_to.push(referent); }
355         }
356         protected static get_ptr_of(o: CommonBase) {
357                 return o.ptr;
358         }
359         protected static set_null_skip_free(o: CommonBase) {
360                 o.ptr = 0n;
361                 // @ts-ignore TypeScript is wrong about the returnvalue of unregister here!
362                 const did_unregister: boolean = finalizer.unregister(o);
363                 if (!did_unregister)
364                         throw new Error("FinalizationRegistry unregister should always unregister unless you double-free'd");
365         }
366 }
367
368 export class UInt5 {
369         public constructor(private val: number) {
370                 if (val > 32 || val < 0) throw new Error("UInt5 value is out of range");
371         }
372         public getVal(): number {
373                 return this.val;
374         }
375 }
376
377 export class WitnessVersion {
378         public constructor(private val: number) {
379                 if (val > 16 || val < 0) throw new Error("WitnessVersion value is out of range");
380         }
381         public getVal(): number {
382                 return this.val;
383         }
384 }
385
386 export class UnqualifiedError {
387         public constructor(val: number) {}
388 }
389 """
390
391         self.txout_defn = """export class TxOut extends CommonBase {
392         /** The script_pubkey in this output */
393         public script_pubkey: Uint8Array;
394         /** The value, in satoshis, of this output */
395         public value: bigint;
396
397         /* @internal */
398         public constructor(_dummy: object, ptr: bigint) {
399                 super(ptr, bindings.TxOut_free);
400                 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
401                 this.value = bindings.TxOut_get_value(ptr);
402         }
403         public static constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
404                 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
405         }
406 }"""
407         self.obj_defined(["TxOut"], "structs")
408
409         self.scalar_defn = """export class BigEndianScalar extends CommonBase {
410         /** The bytes of the scalar value, in big endian */
411         public scalar_bytes: Uint8Array;
412
413         /* @internal */
414         public constructor(_dummy: object, ptr: bigint) {
415                 super(ptr, bindings.BigEndianScalar_free);
416                 this.scalar_bytes = bindings.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
417         }
418         public static constructor_new(scalar_bytes: Uint8Array): BigEndianScalar {
419                 return new BigEndianScalar(null, bindings.BigEndianScalar_new(bindings.encodeUint8Array(scalar_bytes)));
420         }
421 }"""
422         self.obj_defined(["BigEndianScalar"], "structs")
423
424         self.c_file_pfx = """#include "js-wasm.h"
425 #include <stdatomic.h>
426 #include <lightning.h>
427
428 // These should be provided...somehow...
429 void *memset(void *s, int c, size_t n);
430 void *memcpy(void *dest, const void *src, size_t n);
431 int memcmp(const void *s1, const void *s2, size_t n);
432
433 extern void __attribute__((noreturn)) abort(void);
434 static inline void assert(bool expression) {
435         if (!expression) { abort(); }
436 }
437
438 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
439         return val == 0xdeadbeef0badf00dULL;
440 }
441
442 """
443
444         if not DEBUG:
445             self.c_file_pfx += """
446 void *malloc(size_t size);
447 void free(void *ptr);
448
449 #define MALLOC(a, _) malloc(a)
450 #define do_MALLOC(a, _b, _c) malloc(a)
451 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
452 #define DO_ASSERT(a) (void)(a)
453 #define CHECK(a)
454 #define CHECK_ACCESS(p)
455 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
456 """
457         else:
458             self.c_file_pfx += """
459 extern int snprintf(char *str, size_t size, const char *format, ...);
460 typedef int32_t ssize_t;
461 ssize_t write(int fd, const void *buf, size_t count);
462 #define DEBUG_PRINT(...) do { \\
463         char debug_str[1024]; \\
464         int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
465         write(2, debug_str, s_len); \\
466 } while (0);
467
468 // Always run a, then assert it is true:
469 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
470 // Assert a is true or do nothing
471 #define CHECK(a) DO_ASSERT(a)
472
473 // Running a leak check across all the allocations and frees of the JDK is a mess,
474 // so instead we implement our own naive leak checker here, relying on the -wrap
475 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
476 // and free'd in Rust or C across the generated bindings shared library.
477
478 #define BT_MAX 128
479 typedef struct allocation {
480         struct allocation* next;
481         void* ptr;
482         const char* struct_name;
483         int lineno;
484 } allocation;
485 static allocation* allocation_ll = NULL;
486 static allocation* freed_ll = NULL;
487
488 extern void* __real_malloc(size_t len);
489 extern void* __real_calloc(size_t nmemb, size_t len);
490 extern void* __real_aligned_alloc(size_t alignment, size_t size);
491 static void new_allocation(void* res, const char* struct_name, int lineno) {
492         allocation* new_alloc = __real_malloc(sizeof(allocation));
493         new_alloc->ptr = res;
494         new_alloc->struct_name = struct_name;
495         new_alloc->next = allocation_ll;
496         new_alloc->lineno = lineno;
497         allocation_ll = new_alloc;
498 }
499 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
500         void* res = __real_malloc(len);
501         new_allocation(res, struct_name, lineno);
502         return res;
503 }
504 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
505
506 void __real_free(void* ptr);
507 static void alloc_freed(void* ptr, int lineno) {
508         allocation* p = NULL;
509         allocation* it = allocation_ll;
510         while (it->ptr != ptr) {
511                 p = it; it = it->next;
512                 if (it == NULL) {
513                         p = NULL;
514                         it = freed_ll;
515                         while (it && it->ptr != ptr) { p = it; it = it->next; }
516                         if (it == NULL) {
517                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
518                         } else {
519                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n Possibly double-free from %s, allocated on line %d.", ptr, lineno, it->struct_name, it->lineno);
520                         }
521                         abort();
522                 }
523         }
524         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
525         DO_ASSERT(it->ptr == ptr);
526         it->next = freed_ll;
527         freed_ll = it;
528 }
529 static void do_FREE(void* ptr, int lineno) {
530         if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
531         alloc_freed(ptr, lineno);
532         __real_free(ptr);
533 }
534 #define FREE(ptr) do_FREE(ptr, __LINE__)
535
536 static void CHECK_ACCESS(const void* ptr) {
537         allocation* it = allocation_ll;
538         while (it->ptr != ptr) {
539                 it = it->next;
540                 if (it == NULL) {
541                         return; // addrsan should catch malloc-unknown and print more info than we have
542                 }
543         }
544 }
545 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
546         if (v.is_owned && v.inner != NULL) { \\
547                 const void *p = __unmangle_inner_ptr(v.inner); \\
548                 if (p != NULL) { \\
549                         CHECK_ACCESS(p); \\
550                 } \\
551         }
552
553 void* __wrap_malloc(size_t len) {
554         void* res = __real_malloc(len);
555         new_allocation(res, "malloc call", 0);
556         return res;
557 }
558 void* __wrap_calloc(size_t nmemb, size_t len) {
559         void* res = __real_calloc(nmemb, len);
560         new_allocation(res, "calloc call", 0);
561         return res;
562 }
563 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
564         void* res = __real_aligned_alloc(alignment, size);
565         new_allocation(res, "aligned_alloc call", 0);
566         return res;
567 }
568 void __wrap_free(void* ptr) {
569         if (ptr == NULL) return;
570         alloc_freed(ptr, 0);
571         __real_free(ptr);
572 }
573
574 void* __real_realloc(void* ptr, size_t newlen);
575 void* __wrap_realloc(void* ptr, size_t len) {
576         if (ptr != NULL) alloc_freed(ptr, 0);
577         void* res = __real_realloc(ptr, len);
578         new_allocation(res, "realloc call", 0);
579         return res;
580 }
581 void __wrap_reallocarray(void* ptr, size_t new_sz) {
582         // Rust doesn't seem to use reallocarray currently
583         DO_ASSERT(false);
584 }
585
586 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
587         uint32_t count = 0;
588         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
589                 count++;
590         }
591         return count;
592 }
593 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
594         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
595                 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
596         }
597 }
598 """
599         self.c_file_pfx = self.c_file_pfx + """
600 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
601 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
602 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
603 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
604
605 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
606
607 #define DECL_ARR_TYPE(ty, name) \\
608         struct name##array { \\
609                 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
610                 ty elems[]; \\
611         }; \\
612         typedef struct name##array * name##Array; \\
613         static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
614                 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
615                 arr->arr_len = arr_len; \\
616                 return arr; \\
617         }
618
619 DECL_ARR_TYPE(int64_t, int64_t);
620 DECL_ARR_TYPE(uint64_t, uint64_t);
621 DECL_ARR_TYPE(int8_t, int8_t);
622 DECL_ARR_TYPE(uint32_t, uint32_t);
623 DECL_ARR_TYPE(void*, ptr);
624 DECL_ARR_TYPE(char, char);
625 typedef charArray jstring;
626
627 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
628         charArray arr = init_charArray(len, __LINE__);
629         memcpy(arr->elems, chars, len);
630         return arr;
631 }
632 static inline LDKStr str_ref_to_owned_c(const jstring str) {
633         char* newchars = MALLOC(str->arr_len + 1, "String chars");
634         memcpy(newchars, str->elems, str->arr_len);
635         newchars[str->arr_len] = 0;
636         LDKStr res = {
637                 .chars = newchars,
638                 .len = str->arr_len,
639                 .chars_is_owned = true
640         };
641         return res;
642 }
643
644 typedef bool jboolean;
645
646 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
647         return (uint32_t)MALLOC(size, "JS-Called malloc");
648 }
649 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
650         FREE((void*)ptr);
651 }
652
653 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
654         const char *res = check_get_ldk_bindings_version();
655         if (res == NULL) return NULL;
656         return str_ref_to_ts(res, strlen(res));
657 }
658 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
659         const char *res = check_get_ldk_version();
660         if (res == NULL) return NULL;
661         return str_ref_to_ts(res, strlen(res));
662 }
663 #include "version.c"
664 """
665
666         self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
667         return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
668 }"""
669
670         self.hu_struct_file_prefix = """
671 import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBase.mjs';
672 import * as bindings from '../bindings.mjs'
673
674 """
675         self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
676         self.util_fn_sfx = "}"
677         self.c_fn_ty_pfx = ""
678         self.file_ext = ".mts"
679         self.ptr_c_ty = "uint64_t"
680         self.ptr_native_ty = "bigint"
681         self.usize_c_ty = "uint32_t"
682         self.usize_native_ty = "number"
683         self.native_zero_ptr = "0n"
684         self.result_c_ty = "uint32_t"
685         self.ptr_arr = "ptrArray"
686         self.is_arr_some_check = ("", " != 0")
687         self.get_native_arr_len_call = ("", "->arr_len")
688
689     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
690         return None
691     def create_native_arr_call(self, arr_len, ty_info):
692         if ty_info.c_ty == "ptrArray":
693             assert ty_info.rust_obj == "LDKCVec_u5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
694         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
695     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
696         if ty_info.c_ty == "int8_tArray":
697             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
698         else:
699             assert False
700     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
701         if ty_info.c_ty == "int8_tArray":
702             if copy:
703                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
704         assert not copy
705         if ty_info.c_ty == "ptrArray":
706             return "(void*) " + arr_name + "->elems"
707         else:
708             return arr_name + "->elems"
709     def get_native_arr_elem(self, arr_name, idxc, ty_info):
710         assert False # Only called if above is None
711     def get_native_arr_ptr_call(self, ty_info):
712         if ty_info.subty is not None:
713             return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
714         return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
715     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
716         return None
717     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
718         if ty_info.c_ty == "int8_tArray":
719             return "FREE(" + arr_name + ");"
720         else:
721             return "FREE(" + arr_name + ")"
722
723     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
724         if elem_ty.rust_obj == "LDKu5":
725             return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
726         assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array")
727         return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
728
729     def str_ref_to_native_call(self, var_name, str_len):
730         return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
731     def str_ref_to_c_call(self, var_name):
732         return "str_ref_to_owned_c(" + var_name + ")"
733     def str_to_hu_conv(self, var_name):
734         return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
735     def str_from_hu_conv(self, var_name):
736         return ("bindings.encodeString(" + var_name + ")", "")
737
738     def c_fn_name_define_pfx(self, fn_name, have_args):
739         return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
740
741     def init_str(self):
742         return ""
743
744     def get_java_arr_len(self, arr_name):
745         return "bindings.getArrayLength(" + arr_name + ")"
746     def get_java_arr_elem(self, elem_ty, arr_name, idx):
747         if elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t":
748             return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
749         elif elem_ty.c_ty == "uint64_t":
750             return "bindings.getU64ArrayElem(" + arr_name + ", " + idx + ")"
751         elif elem_ty.rust_obj == "LDKu5":
752             return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
753         else:
754             assert False
755     def constr_hu_array(self, ty_info, arr_len):
756         return "new Array(" + arr_len + ").fill(null)"
757     def cleanup_converted_native_array(self, ty_info, arr_name):
758         return "bindings.freeWasmMemory(" + arr_name + ")"
759
760     def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
761         inner = arr_name
762         if fixed_len is not None:
763             assert mapped_ty.c_ty == "int8_t"
764             inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
765         if mapped_ty.c_ty.endswith("Array"):
766             return ("bindings.encodeUint32Array(" + inner + ")", "")
767         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
768             return ("bindings.encodeUint8Array(" + inner + ")", "")
769         elif mapped_ty.c_ty == "uint32_t":
770             return ("bindings.encodeUint32Array(" + inner + ")", "")
771         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t":
772             return ("bindings.encodeUint64Array(" + inner + ")", "")
773         else:
774             print(mapped_ty.c_ty)
775             assert False
776
777     def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
778         if mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
779             return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
780         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
781             return "const " + conv_name + ": bigint[] = bindings.decodeUint64Array(" + arr_name + ");"
782         else:
783             assert False
784
785     def var_decl_statement(self, ty_string, var_name, statement):
786         return "const " + var_name + ": " + ty_string + " = " + statement
787
788     def java_arr_ty_str(self, elem_ty_str):
789         return "number"
790
791     def for_n_in_range(self, n, minimum, maximum):
792         return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
793     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
794         return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
795
796     def get_ptr(self, var):
797         return "CommonBase.get_ptr_of(" + var + ")"
798     def set_null_skip_free(self, var):
799         return "CommonBase.set_null_skip_free(" + var + ");"
800
801     def add_ref(self, holder, referent):
802         return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
803
804     def obj_defined(self, struct_names, folder):
805         with open(self.outdir + "/index.mts", 'a') as index:
806             index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
807         with open(self.outdir + "/imports.mts.part", 'a') as imports:
808             imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
809
810     def fully_qualified_hu_ty_path(self, ty):
811         return ty.java_hu_ty
812
813     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
814         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
815         out_c = out_c + "\tswitch (ord) {\n"
816         ord_v = 0
817
818         out_typescript_enum_fields = ""
819
820         for var, var_docs in variants:
821             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
822             ord_v = ord_v + 1
823             if var_docs is not None:
824                 var_docs_repld = var_docs.replace("\n", "\n\t")
825                 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
826             out_typescript_enum_fields += f"\t{var},\n\t"
827         out_c = out_c + "\t}\n"
828         out_c = out_c + "\tabort();\n"
829         out_c = out_c + "}\n"
830
831         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
832         out_c = out_c + "\tswitch (val) {\n"
833         ord_v = 0
834         for var, _ in variants:
835             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
836             ord_v = ord_v + 1
837         out_c = out_c + "\t\tdefault: abort();\n"
838         out_c = out_c + "\t}\n"
839         out_c = out_c + "}\n"
840
841         # Note that this is *not* marked /* @internal */ as we re-expose it directly in enums/
842         enum_comment_formatted = enum_doc_comment.replace("\n", "\n * ")
843         out_typescript = f"""
844 /**
845  * {enum_comment_formatted}
846  */
847 export enum {struct_name} {{
848         {out_typescript_enum_fields}
849 }}
850 """
851         out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
852         self.obj_defined([struct_name], "enums")
853         return (out_c, out_typescript_enum, out_typescript)
854
855     def c_unitary_enum_to_native_call(self, ty_info):
856         return (ty_info.rust_obj + "_to_js(", ")")
857     def native_unitary_enum_to_c_call(self, ty_info):
858         return (ty_info.rust_obj + "_from_js(", ")")
859
860     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
861         out_typescript_bindings = ""
862         super_instantiator = ""
863         bindings_instantiator = ""
864         pointer_to_adder = ""
865         impl_constructor_arguments = ""
866         for var in flattened_field_var_conversions:
867             if isinstance(var, ConvInfo):
868                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
869                 super_instantiator += first_to_lower(var.arg_name) + ", "
870                 if var.from_hu_conv is not None:
871                     bindings_instantiator += ", " + var.from_hu_conv[0]
872                     if var.from_hu_conv[1] != "":
873                         pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
874                 else:
875                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
876             else:
877                 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
878                 super_instantiator += first_to_lower(var[1]) + "_impl, "
879                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
880                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
881
882         super_constructor_statements = ""
883         trait_constructor_arguments = ""
884         for var in field_var_conversions:
885             if isinstance(var, ConvInfo):
886                 trait_constructor_arguments += ", " + var.arg_name
887             else:
888                 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
889                 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
890                 for suparg in var[2]:
891                     if isinstance(suparg, ConvInfo):
892                         trait_constructor_arguments += ", " + suparg.arg_name
893                     else:
894                         trait_constructor_arguments += ", " + suparg[1]
895
896         # BUILD INTERFACE METHODS
897         out_java_interface = ""
898         out_interface_implementation_overrides = ""
899         java_methods = []
900         for fn_line in field_function_lines:
901             java_method_descriptor = ""
902             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
903                 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
904                 out_java_interface += "\t" + fn_line.fn_name + "("
905                 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
906
907                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
908                     if idx >= 1:
909                         out_java_interface += ", "
910                         out_interface_implementation_overrides += ", "
911                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
912                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
913                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
914                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
915                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
916                 java_methods.append((fn_line.fn_name, java_method_descriptor))
917
918                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
919
920                 for arg_info in fn_line.args_ty:
921                     if arg_info.to_hu_conv is not None:
922                         out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
923
924                 if fn_line.ret_ty_info.java_ty != "void":
925                     out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
926                 else:
927                     out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
928
929                 for idx, arg_info in enumerate(fn_line.args_ty):
930                     if idx != 0:
931                         out_interface_implementation_overrides += ", "
932                     if arg_info.to_hu_conv_name is not None:
933                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
934                     else:
935                         out_interface_implementation_overrides += arg_info.arg_name
936
937                 out_interface_implementation_overrides += ");\n"
938                 if fn_line.ret_ty_info.java_ty != "void":
939                     if fn_line.ret_ty_info.from_hu_conv is not None:
940                         out_interface_implementation_overrides += "\t\t\t\t" + f"const result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0].replace("\n", "\n\t\t\t\t") + ";\n"
941                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
942                             out_interface_implementation_overrides += "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held").replace("\n", "\n\t\t\t\t") + ";\n"
943                         #if fn_line.ret_ty_info.rust_obj in result_types:
944                         # XXX: We need to handle this in conversion logic so that its cross-language!
945                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
946                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
947                         out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
948                     else:
949                         out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
950                 out_interface_implementation_overrides += f"\t\t\t}},\n"
951
952         formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
953         out_typescript_human = f"""
954 {self.hu_struct_file_prefix}
955
956 /** An implementation of {struct_name.replace("LDK","")} */
957 export interface {struct_name.replace("LDK", "")}Interface {{
958 {out_java_interface}}}
959
960 class {struct_name}Holder {{
961         held: {struct_name.replace("LDK", "")};
962 }}
963
964 /**
965  * {formatted_trait_docs}
966  */
967 export class {struct_name.replace("LDK","")} extends CommonBase {{
968         /* @internal */
969         public bindings_instance?: bindings.{struct_name};
970
971         /* @internal */
972         public instance_idx?: number;
973
974         /* @internal */
975         constructor(_dummy: object, ptr: bigint) {{
976                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
977                 this.bindings_instance = null;
978         }}
979
980         /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
981         public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
982                 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
983                 let structImplementation = {{
984 {out_interface_implementation_overrides}                }} as bindings.{struct_name};
985 {super_constructor_statements}          const ptr_idx: [bigint, number] = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
986
987                 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
988                 impl_holder.held.instance_idx = ptr_idx[1];
989                 impl_holder.held.bindings_instance = structImplementation;
990 {pointer_to_adder}              return impl_holder.held;
991         }}
992
993 """
994         self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
995
996         out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
997         java_meths = []
998         for fn_line in field_function_lines:
999             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1000                 out_typescript_bindings += f"\t{fn_line.fn_name} ("
1001
1002                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
1003                     if idx >= 1:
1004                         out_typescript_bindings = out_typescript_bindings + ", "
1005                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1006
1007                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
1008
1009         out_typescript_bindings += "}\n\n"
1010
1011         c_call_extra_args = ""
1012         out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
1013         for var in flattened_field_var_conversions:
1014             if isinstance(var, ConvInfo):
1015                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
1016                 c_call_extra_args += f", {var.arg_name}"
1017             else:
1018                 out_typescript_bindings += f", {var[1]}: number"
1019                 c_call_extra_args += f", {var[1]}"
1020
1021
1022         out_typescript_bindings += f"""): [bigint, number] {{
1023         if(!isWasmInitialized) {{
1024                 throw new Error("initializeWasm() must be awaited first!");
1025         }}
1026         var new_obj_idx = js_objs.length;
1027         for (var i = 0; i < js_objs.length; i++) {{
1028                 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
1029         }}
1030         js_objs[i] = new WeakRef(impl);
1031         return [wasm.TS_{struct_name}_new(i{c_call_extra_args}), i];
1032 }}
1033 """
1034
1035         # Now that we've written out our java code (and created java_meths), generate C
1036         out_c = "typedef struct " + struct_name + "_JCalls {\n"
1037         out_c += "\tatomic_size_t refcnt;\n"
1038         out_c += "\tuint32_t instance_ptr;\n"
1039         for var in flattened_field_var_conversions:
1040             if isinstance(var, ConvInfo):
1041                 # We're a regular ol' field
1042                 pass
1043             else:
1044                 # We're a supertrait
1045                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
1046         out_c = out_c + "} " + struct_name + "_JCalls;\n"
1047
1048         for fn_line in field_function_lines:
1049             if fn_line.fn_name == "free":
1050                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
1051                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1052                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
1053                 out_c = out_c + "\t\tFREE(j_calls);\n"
1054                 out_c = out_c + "\t}\n}\n"
1055
1056         for idx, fn_line in enumerate(field_function_lines):
1057             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1058                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
1059                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
1060                 if fn_line.self_is_const:
1061                     out_c = out_c + "const void* this_arg"
1062                 else:
1063                     out_c = out_c + "void* this_arg"
1064
1065                 for idx, arg in enumerate(fn_line.args_ty):
1066                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
1067
1068                 out_c = out_c + ") {\n"
1069                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1070
1071                 for arg_info in fn_line.args_ty:
1072                     if arg_info.ret_conv is not None:
1073                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
1074                         out_c = out_c + arg_info.arg_name
1075                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
1076
1077                 fn_suffix = ""
1078                 assert len(fn_line.args_ty) < 6
1079                 for arg_info in fn_line.args_ty:
1080                     if arg_info.c_ty == "uint64_t" or arg_info.c_ty == "int64_t":
1081                         fn_suffix += "b"
1082                     else:
1083                         fn_suffix += "u"
1084                 for i in range(0, 6 - len(fn_line.args_ty)):
1085                     fn_suffix += "u"
1086                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
1087                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
1088                     out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1089                 elif fn_line.ret_ty_info.java_ty == "void":
1090                     out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1091                 elif fn_line.ret_ty_info.java_hu_ty == "string":
1092                     out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1093                 elif fn_line.ret_ty_info.arg_conv is None:
1094                     out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1095                 else:
1096                     out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1097
1098                 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
1099                 self.function_ptr_counter += 1
1100
1101                 for idx, arg_info in enumerate(fn_line.args_ty):
1102                     if arg_info.ret_conv is not None:
1103                         if arg_info.c_ty.endswith("Array"):
1104                             out_c += ", (uint32_t)" + arg_info.ret_conv_name
1105                         else:
1106                             out_c += ", " + arg_info.ret_conv_name
1107                     else:
1108                         assert False # TODO: Would we need some conversion here?
1109                         out_c += ", (uint32_t)" + arg_info.arg_name
1110                 for i in range(0, 6 - len(fn_line.args_ty)):
1111                     out_c += ", 0"
1112                 out_c = out_c + ");\n"
1113                 if fn_line.ret_ty_info.arg_conv is not None:
1114                     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"
1115
1116                 out_c = out_c + "}\n"
1117
1118         # Write out a clone function whether we need one or not, as we use them in moving to rust
1119         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1120         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1121         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1122         for var in field_var_conversions:
1123             if not isinstance(var, ConvInfo):
1124                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
1125         out_c = out_c + "}\n"
1126
1127         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
1128         for var in flattened_field_var_conversions:
1129             if isinstance(var, ConvInfo):
1130                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1131             else:
1132                 out_c = out_c + ", JSValue " + var[1]
1133         out_c = out_c + ") {\n"
1134
1135         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1136         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1137         out_c = out_c + "\tcalls->instance_ptr = o;\n"
1138
1139         for (fn_name, java_meth_descr) in java_meths:
1140             if fn_name != "free" and fn_name != "cloned":
1141                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1142                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1143
1144         for var in flattened_field_var_conversions:
1145             if isinstance(var, ConvInfo) and var.arg_conv is not None:
1146                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1147         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1148         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1149         for fn_line in field_function_lines:
1150             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1151                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1152             elif fn_line.fn_name == "free":
1153                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1154             else:
1155                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1156         for var in field_var_conversions:
1157             if isinstance(var, ConvInfo):
1158                 if var.arg_conv_name is not None:
1159                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1160                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1161                 else:
1162                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1163                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1164             else:
1165                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1166                 for suparg in var[2]:
1167                     if isinstance(suparg, ConvInfo):
1168                         out_c += ", " + suparg.arg_name
1169                     else:
1170                         out_c += ", " + suparg[1]
1171                 out_c += "),\n"
1172         out_c = out_c + "\t};\n"
1173         for var in flattened_field_var_conversions:
1174             if not isinstance(var, ConvInfo):
1175                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1176         out_c = out_c + "\treturn ret;\n"
1177         out_c = out_c + "}\n"
1178
1179         out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1180         for var in flattened_field_var_conversions:
1181             if isinstance(var, ConvInfo):
1182                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1183             else:
1184                 out_c = out_c + ", JSValue " + var[1]
1185         out_c = out_c + ") {\n"
1186         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1187         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1188         for var in flattened_field_var_conversions:
1189             if isinstance(var, ConvInfo):
1190                 out_c = out_c + ", " + var.arg_name
1191             else:
1192                 out_c = out_c + ", " + var[1]
1193         out_c = out_c + ");\n"
1194         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1195         out_c = out_c + "}\n"
1196
1197         return (out_typescript_bindings, out_typescript_human, out_c)
1198
1199     def trait_struct_inc_refcnt(self, ty_info):
1200         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1201         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1202         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1203         return base_conv
1204
1205     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1206         bindings_type = struct_name.replace("LDK", "")
1207         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1208
1209         out_java_enum = ""
1210         out_java = ""
1211         out_c = ""
1212
1213         out_java_enum += (self.hu_struct_file_prefix)
1214
1215         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1216         java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1217         java_hu_class += "\tprotected constructor(_dummy: object, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
1218         java_hu_class += "\t/* @internal */\n"
1219         java_hu_class += f"\tpublic static constr_from_ptr(ptr: bigint): {java_hu_type} {{\n"
1220         java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1221         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"
1222         out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1223         out_c += "\tswitch(obj->tag) {\n"
1224         java_hu_class += "\t\tswitch (raw_ty) {\n"
1225         java_hu_subclasses = ""
1226
1227         out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1228         out_java += "\tprotected constructor() {}\n"
1229         var_idx = 0
1230         for var in variant_list:
1231             java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1232             java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1233             java_hu_class += f"\t\t\tcase {var_idx}: "
1234             java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1235             out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1236             hu_conv_body = ""
1237             for idx, (field_ty, field_docs) in enumerate(var.fields):
1238                 if field_docs is not None:
1239                     java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1240                 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1241                 if field_ty.to_hu_conv is not None:
1242                     hu_conv_body += f"\t\tconst {field_ty.arg_name}: {field_ty.java_ty} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1243                     hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1244                     hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1245                 else:
1246                     hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1247             java_hu_subclasses += "\t/* @internal */\n"
1248             java_hu_subclasses += "\tpublic constructor(ptr: bigint) {\n\t\tsuper(null, ptr);\n"
1249             java_hu_subclasses = java_hu_subclasses + hu_conv_body
1250             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1251             var_idx += 1
1252         out_java += "}\n"
1253         java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t\t}\n\t}\n\n"
1254         out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: bigint", "ptr")
1255         out_c += ("\t\tdefault: abort();\n")
1256         out_c += ("\t}\n}\n")
1257
1258         for var in variant_list:
1259             for idx, (field_map, _) in enumerate(var.fields):
1260                 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1261                 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"
1262                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1263                 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1264                 if field_map.ret_conv is not None:
1265                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1266                     if var.tuple_variant:
1267                         out_c += "obj->" + camel_to_snake(var.var_name)
1268                     else:
1269                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1270                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1271                     out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1272                 else:
1273                     if var.tuple_variant:
1274                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1275                     else:
1276                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1277                 out_c += "}\n"
1278                 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: bigint", "ptr")
1279         out_java_enum += java_hu_class
1280         self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1281         self.obj_defined([java_hu_type], "structs")
1282         return (out_java, out_java_enum, out_c)
1283
1284     def map_opaque_struct(self, struct_name, struct_doc_comment):
1285         implementations = ""
1286         method_header = ""
1287
1288         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1289         out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1290         constructor_body = "super(ptr, bindings." + struct_name.replace("LDK","") + "_free);"
1291         extra_docs = ""
1292         extra_body = ""
1293         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1294             extra_docs = "\n * This type represents a lock and MUST BE MANUALLY FREE'd!"
1295             constructor_body = 'super(ptr, () => { throw new Error("Locks must be manually freed with free()"); });'
1296             extra_body = f"""
1297         /** Releases this lock */
1298         public free() {{
1299                 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
1300                 CommonBase.set_null_skip_free(this);
1301         }}"""
1302         formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1303         out_opaque_struct_human += f"""
1304 /**{extra_docs}
1305  * {formatted_doc_comment}
1306  */
1307 export class {hu_name} extends CommonBase {implementations}{{
1308         /* @internal */
1309         public constructor(_dummy: object, ptr: bigint) {{
1310                 {constructor_body}
1311         }}{extra_body}
1312
1313 """
1314         self.obj_defined([hu_name], "structs")
1315         return out_opaque_struct_human
1316
1317     def map_tuple(self, struct_name):
1318         return self.map_opaque_struct(struct_name, "A Tuple")
1319
1320     def map_result(self, struct_name, res_map, err_map):
1321         human_ty = struct_name.replace("LDKCResult", "Result")
1322
1323         suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1324         if res_map.java_hu_ty != "void":
1325             suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1326         suffixes += f"""
1327         /* @internal */
1328         public constructor(_dummy: object, ptr: bigint) {{
1329                 super(_dummy, ptr);
1330 """
1331         if res_map.java_hu_ty == "void":
1332             pass
1333         elif res_map.to_hu_conv is not None:
1334             suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1335             suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1336             suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1337         else:
1338             suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1339         suffixes += "\t}\n}\n"
1340
1341         suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1342         if err_map.java_hu_ty != "void":
1343             suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1344         suffixes += f"""
1345         /* @internal */
1346         public constructor(_dummy: object, ptr: bigint) {{
1347                 super(_dummy, ptr);
1348 """
1349         if err_map.java_hu_ty == "void":
1350             pass
1351         elif err_map.to_hu_conv is not None:
1352             suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1353             suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1354             suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1355         else:
1356             suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1357         suffixes += "\t}\n}"
1358
1359         self.struct_file_suffixes[human_ty] = suffixes
1360         self.obj_defined([human_ty], "structs")
1361
1362         return f"""{self.hu_struct_file_prefix}
1363
1364 export class {human_ty} extends CommonBase {{
1365         protected constructor(_dummy: object, ptr: bigint) {{
1366                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1367         }}
1368         /* @internal */
1369         public static constr_from_ptr(ptr: bigint): {human_ty} {{
1370                 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1371                         return new {human_ty}_OK(null, ptr);
1372                 }} else {{
1373                         return new {human_ty}_Err(null, ptr);
1374                 }}
1375         }}
1376 """
1377
1378     def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1379         has_return_value = return_c_ty != 'void'
1380         return_statement = 'return nativeResponseValue;'
1381         if not has_return_value:
1382             return_statement = '// debug statements here'
1383
1384         return f"""/* @internal */
1385 export function {method_name}({method_argument_string}): {return_java_ty} {{
1386         if(!isWasmInitialized) {{
1387                 throw new Error("initializeWasm() must be awaited first!");
1388         }}
1389         const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1390         {return_statement}
1391 }}
1392 """
1393     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):
1394         out_java = ""
1395         out_c = ""
1396         out_java_struct = None
1397
1398         out_java += ("\t")
1399         out_c += (self.c_fn_ty_pfx)
1400         out_c += (return_type_info.c_ty)
1401         out_java += (return_type_info.java_ty)
1402         if return_type_info.ret_conv is not None:
1403             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1404         out_java += (" " + method_name + "(")
1405         out_c += (" "  + self.c_fn_name_define_pfx(method_name, True))
1406
1407         method_argument_string = ""
1408         native_call_argument_string = ""
1409         for idx, arg_conv_info in enumerate(argument_types):
1410             if idx != 0:
1411                 method_argument_string += (", ")
1412                 native_call_argument_string += ', '
1413                 out_c += (", ")
1414             if arg_conv_info.c_ty != "void":
1415                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1416                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1417                 native_call_argument_string += arg_conv_info.arg_name
1418         out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1419
1420         out_java_struct = ""
1421         if doc_comment is not None:
1422             out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1423
1424         if not args_known:
1425             out_java_struct += ("\t// Skipped " + method_name + "\n")
1426         else:
1427             if not takes_self:
1428                 out_java_struct += (
1429                         "\tpublic static constructor_" + meth_n + "(")
1430             else:
1431                 out_java_struct += ("\tpublic " + meth_n + "(")
1432             for idx, arg in enumerate(argument_types):
1433                 if idx != 0:
1434                     if not takes_self or idx > 1:
1435                         out_java_struct += (", ")
1436                 elif takes_self:
1437                     continue
1438                 if arg.java_ty != "void":
1439                     if arg.arg_name in default_constructor_args:
1440                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1441                             if explode_idx != 0:
1442                                 out_java_struct += (", ")
1443                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1444                     else:
1445                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1446
1447         out_c += (") {\n")
1448         if out_java_struct is not None:
1449             out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1450         for info in argument_types:
1451             if info.arg_conv is not None:
1452                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1453         if return_type_info.ret_conv is not None:
1454             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1455         elif return_type_info.c_ty != "void":
1456             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1457         else:
1458             out_c += ("\t")
1459         if c_call_string is None:
1460             out_c += (method_name + "(")
1461         else:
1462             out_c += (c_call_string)
1463         for idx, info in enumerate(argument_types):
1464             if info.arg_conv_name is not None:
1465                 if idx != 0:
1466                     out_c += (", ")
1467                 elif c_call_string is not None:
1468                     continue
1469                 out_c += (info.arg_conv_name)
1470         out_c += (")")
1471         if return_type_info.ret_conv is not None:
1472             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1473         else:
1474             out_c += (";")
1475         for info in argument_types:
1476             if info.arg_conv_cleanup is not None:
1477                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1478         if return_type_info.ret_conv is not None:
1479             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1480         elif return_type_info.c_ty != "void":
1481             out_c += ("\n\treturn ret_val;")
1482         out_c += ("\n}\n\n")
1483
1484         if args_known:
1485             out_java_struct += ("\t\t")
1486             if return_type_info.java_ty != "void":
1487                 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1488             out_java_struct += ("bindings." + method_name + "(")
1489             for idx, info in enumerate(argument_types):
1490                 if idx != 0:
1491                     out_java_struct += (", ")
1492                 if idx == 0 and takes_self:
1493                     out_java_struct += ("this.ptr")
1494                 elif info.arg_name in default_constructor_args:
1495                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1496                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1497                         if explode_idx != 0:
1498                             out_java_struct += (", ")
1499                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1500                         if explode_arg.from_hu_conv is not None:
1501                             out_java_struct += (
1502                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1503                         else:
1504                             out_java_struct += (expl_arg_name)
1505                     out_java_struct += (")")
1506                 elif info.from_hu_conv is not None:
1507                     out_java_struct += (info.from_hu_conv[0])
1508                 else:
1509                     out_java_struct += (info.arg_name)
1510             out_java_struct += (");\n")
1511             if return_type_info.to_hu_conv is not None:
1512                 if not takes_self:
1513                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1514                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1515                 else:
1516                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1517
1518             for idx, info in enumerate(argument_types):
1519                 if idx == 0 and takes_self:
1520                     pass
1521                 elif info.arg_name in default_constructor_args:
1522                     for explode_arg in default_constructor_args[info.arg_name]:
1523                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1524                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1525                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1526                                                                                              expl_arg_name).replace(
1527                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1528                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1529                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1530                         out_java_struct += (
1531                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1532                     else:
1533                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1534
1535             if return_type_info.to_hu_conv_name is not None:
1536                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1537             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1538                 out_java_struct += ("\t\treturn ret;\n")
1539             out_java_struct += ("\t}\n\n")
1540
1541         return (out_java, out_c, out_java_struct)
1542
1543     def cleanup(self):
1544         for struct in self.struct_file_suffixes:
1545             with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1546                 src.write(self.struct_file_suffixes[struct])
1547
1548         with open(self.outdir + "/bindings.mts", "a") as bindings:
1549             bindings.write("""
1550
1551 js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2: bigint|number, arg3: bigint|number, arg4: bigint|number, arg5: bigint|number, arg6: bigint|number, arg7: bigint|number, arg8: bigint|number, arg9: bigint|number, arg10: bigint|number) {
1552         const weak: WeakRef<object> = js_objs[obj_ptr];
1553         if (weak == null || weak == undefined) {
1554                 console.error("Got function call on unknown/free'd JS object!");
1555                 throw new Error("Got function call on unknown/free'd JS object!");
1556         }
1557         const obj: object = weak.deref();
1558         if (obj == null || obj == undefined) {
1559                 console.error("Got function call on GC'd JS object!");
1560                 throw new Error("Got function call on GC'd JS object!");
1561         }
1562         var fn;
1563 """)
1564             bindings.write("\tswitch (fn_id) {\n")
1565             for f in self.function_ptrs:
1566                 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1567
1568             bindings.write("""\t\tdefault:
1569                         console.error("Got unknown function call from C!");
1570                         throw new Error("Got unknown function call from C!");
1571         }
1572         if (fn == null || fn == undefined) {
1573                 console.error("Got function call on incorrect JS object!");
1574                 throw new Error("Got function call on incorrect JS object!");
1575         }
1576         const ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
1577         if (ret === undefined || ret === null) return BigInt(0);
1578         return BigInt(ret);
1579 }""")