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