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