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