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