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