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