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