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