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