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