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