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