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