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