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