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