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