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