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