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