270eeccc85c30ad486e782abc82509f5b62c35b4
[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) > 4096) { 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 <= 4096) 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, var_docs in variants:
476             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
477             ord_v = ord_v + 1
478             if var_docs is not None:
479                 out_typescript_enum_fields += f"/**\n * {var_docs}\n */\n"
480             out_typescript_enum_fields += f"{var},\n\t\t\t\t"
481         out_c = out_c + "\t}\n"
482         out_c = out_c + "\tabort();\n"
483         out_c = out_c + "}\n"
484
485         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
486         out_c = out_c + "\tswitch (val) {\n"
487         ord_v = 0
488         for var, _ in variants:
489             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
490             ord_v = ord_v + 1
491         out_c = out_c + "\t\tdefault: abort();\n"
492         out_c = out_c + "\t}\n"
493         out_c = out_c + "}\n"
494
495         out_typescript_enum = f"""
496             export enum {struct_name} {{
497                 {out_typescript_enum_fields}
498             }}
499 """
500
501         return (out_c, out_typescript_enum, "")
502
503     def c_unitary_enum_to_native_call(self, ty_info):
504         return (ty_info.rust_obj + "_to_js(", ")")
505     def native_unitary_enum_to_c_call(self, ty_info):
506         return (ty_info.rust_obj + "_from_js(", ")")
507
508     def c_complex_enum_pass_ty(self, struct_name):
509         return "uint32_t"
510
511     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
512         ret = "0 /* " + struct_name + " - " + variant + " */"
513         for param in c_params:
514             ret = ret + "; (void) " + param
515         return ret
516
517     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
518         out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
519
520         constructor_arguments = ""
521         super_instantiator = ""
522         pointer_to_adder = ""
523         impl_constructor_arguments = ""
524         for var in flattened_field_var_conversions:
525             if isinstance(var, ConvInfo):
526                 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
527                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
528                 if var.from_hu_conv is not None:
529                     super_instantiator += ", " + var.from_hu_conv[0]
530                     if var.from_hu_conv[1] != "":
531                         pointer_to_adder += var.from_hu_conv[1] + ";\n"
532                 else:
533                     super_instantiator += ", " + first_to_lower(var.arg_name)
534             else:
535                 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
536                 super_instantiator += ", " + first_to_lower(var[1])
537                 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
538                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
539
540         # BUILD INTERFACE METHODS
541         out_java_interface = ""
542         out_interface_implementation_overrides = ""
543         java_methods = []
544         for fn_line in field_function_lines:
545             java_method_descriptor = ""
546             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
547                 out_java_interface += fn_line.fn_name + "("
548                 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
549
550                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
551                     if idx >= 1:
552                         out_java_interface += ", "
553                         out_interface_implementation_overrides += ", "
554                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
555                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
556                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
557                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
558                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
559                 java_methods.append((fn_line.fn_name, java_method_descriptor))
560
561                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
562
563                 interface_method_override_inset = "\t\t\t\t\t\t"
564                 interface_implementation_inset = "\t\t\t\t\t\t\t"
565                 for arg_info in fn_line.args_ty:
566                     if arg_info.to_hu_conv is not None:
567                         out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
568
569                 if fn_line.ret_ty_info.java_ty != "void":
570                     out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
571                 else:
572                     out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
573
574                 for idx, arg_info in enumerate(fn_line.args_ty):
575                     if idx != 0:
576                         out_interface_implementation_overrides += ", "
577                     if arg_info.to_hu_conv_name is not None:
578                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
579                     else:
580                         out_interface_implementation_overrides += arg_info.arg_name
581
582                 out_interface_implementation_overrides += ");\n"
583                 if fn_line.ret_ty_info.java_ty != "void":
584                     if fn_line.ret_ty_info.from_hu_conv is not None:
585                         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"
586                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
587                             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"
588                         #if fn_line.ret_ty_info.rust_obj in result_types:
589                         # XXX: We need to handle this in conversion logic so that its cross-language!
590                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
591                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
592                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
593                     else:
594                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
595                 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
596
597         trait_constructor_arguments = ""
598         for var in field_var_conversions:
599             if isinstance(var, ConvInfo):
600                 trait_constructor_arguments += ", " + var.arg_name
601             else:
602                 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
603                 for suparg in var[2]:
604                     if isinstance(suparg, ConvInfo):
605                         trait_constructor_arguments += ", " + suparg.arg_name
606                     else:
607                         trait_constructor_arguments += ", " + suparg[1]
608                 trait_constructor_arguments += ").bindings_instance"
609                 for suparg in var[2]:
610                     if isinstance(suparg, ConvInfo):
611                         trait_constructor_arguments += ", " + suparg.arg_name
612                     else:
613                         trait_constructor_arguments += ", " + suparg[1]
614
615         out_typescript_human = f"""
616             {self.hu_struct_file_prefix}
617
618             export class {struct_name.replace("LDK","")} extends CommonBase {{
619
620                 bindings_instance?: bindings.{struct_name};
621
622                 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
623                     if (Number.isFinite(ptr)) {{
624                                         super(ptr);
625                                         this.bindings_instance = null;
626                                     }} else {{
627                                         // TODO: private constructor instantiation
628                                         super(bindings.{struct_name}_new(arg{super_instantiator}));
629                                         this.ptrs_to.push(arg);
630                                         {pointer_to_adder}
631                                     }}
632                 }}
633
634                 protected finalize() {{
635                     if (this.ptr != 0) {{
636                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
637                     }}
638                     super.finalize();
639                 }}
640
641                 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
642                     const impl_holder: {struct_name}Holder = new {struct_name}Holder();
643                     let structImplementation = <bindings.{struct_name}>{{
644                         // todo: in-line interface filling
645                         {out_interface_implementation_overrides}
646                     }};
647                     impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
648                 }}
649             }}
650
651             export interface {struct_name.replace("LDK", "")}Interface {{
652                 {out_java_interface}
653             }}
654
655             class {struct_name}Holder {{
656                 held: {struct_name.replace("LDK", "")};
657             }}
658 """
659
660         out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
661         java_meths = []
662         for fn_line in field_function_lines:
663             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
664                 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
665
666                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
667                     if idx >= 1:
668                         out_typescript_bindings = out_typescript_bindings + ", "
669                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
670
671                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
672
673         out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
674
675         out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
676         for var in flattened_field_var_conversions:
677             if isinstance(var, ConvInfo):
678                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
679             else:
680                 out_typescript_bindings += f", {var[1]}: {var[0]}"
681
682         out_typescript_bindings += f"""): number {{
683             throw new Error('unimplemented'); // TODO: bind to WASM
684         }}
685 """
686
687         out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
688
689         # Now that we've written out our java code (and created java_meths), generate C
690         out_c = "typedef struct " + struct_name + "_JCalls {\n"
691         out_c = out_c + "\tatomic_size_t refcnt;\n"
692         for var in flattened_field_var_conversions:
693             if isinstance(var, ConvInfo):
694                 # We're a regular ol' field
695                 pass
696             else:
697                 # We're a supertrait
698                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
699         for fn in field_function_lines:
700             if fn.fn_name != "free" and fn.fn_name != "cloned":
701                 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
702         out_c = out_c + "} " + struct_name + "_JCalls;\n"
703
704         for fn_line in field_function_lines:
705             if fn_line.fn_name == "free":
706                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
707                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
708                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
709                 for fn in field_function_lines:
710                     if fn.fn_name != "free" and fn.fn_name != "cloned":
711                         out_c = out_c + "\t\tjs_free(j_calls->" + fn.fn_name + "_meth);\n"
712                 out_c = out_c + "\t\tFREE(j_calls);\n"
713                 out_c = out_c + "\t}\n}\n"
714
715         for idx, fn_line in enumerate(field_function_lines):
716             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
717                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
718                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
719                 if fn_line.self_is_const:
720                     out_c = out_c + "const void* this_arg"
721                 else:
722                     out_c = out_c + "void* this_arg"
723
724                 for idx, arg in enumerate(fn_line.args_ty):
725                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
726
727                 out_c = out_c + ") {\n"
728                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
729
730                 for arg_info in fn_line.args_ty:
731                     if arg_info.ret_conv is not None:
732                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
733                         out_c = out_c + arg_info.arg_name
734                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
735
736                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
737                     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"
738                 elif fn_line.ret_ty_info.java_ty == "void":
739                     out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
740                 elif fn_line.ret_ty_info.java_ty == "String":
741                     out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
742                 elif not fn_line.ret_ty_info.passed_as_ptr:
743                     out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
744                 else:
745                     out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
746
747                 for idx, arg_info in enumerate(fn_line.args_ty):
748                     if arg_info.ret_conv is not None:
749                         out_c = out_c + ", " + arg_info.ret_conv_name
750                     else:
751                         out_c = out_c + ", " + arg_info.arg_name
752                 out_c = out_c + ");\n"
753                 if fn_line.ret_ty_info.arg_conv is not None:
754                     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"
755
756                 out_c = out_c + "}\n"
757
758         # Write out a clone function whether we need one or not, as we use them in moving to rust
759         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
760         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
761         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
762         for var in field_var_conversions:
763             if not isinstance(var, ConvInfo):
764                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
765         out_c = out_c + "}\n"
766
767         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
768         for var in flattened_field_var_conversions:
769             if isinstance(var, ConvInfo):
770                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
771             else:
772                 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
773         out_c = out_c + ") {\n"
774
775         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
776         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
777         out_c = out_c + "\t//TODO: Assign calls->o from o\n"
778
779         for (fn_name, java_meth_descr) in java_meths:
780             if fn_name != "free" and fn_name != "cloned":
781                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
782                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
783
784         for var in flattened_field_var_conversions:
785             if isinstance(var, ConvInfo) and var.arg_conv is not None:
786                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
787         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
788         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
789         for fn_line in field_function_lines:
790             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
791                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
792             elif fn_line.fn_name == "free":
793                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
794             else:
795                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
796         for var in field_var_conversions:
797             if isinstance(var, ConvInfo):
798                 if var.arg_conv_name is not None:
799                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
800                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
801                 else:
802                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
803                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
804             else:
805                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
806                 for suparg in var[2]:
807                     if isinstance(suparg, ConvInfo):
808                         out_c += ", " + suparg.arg_name
809                     else:
810                         out_c += ", " + suparg[1]
811                 out_c += "),\n"
812         out_c = out_c + "\t};\n"
813         for var in flattened_field_var_conversions:
814             if not isinstance(var, ConvInfo):
815                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
816         out_c = out_c + "\treturn ret;\n"
817         out_c = out_c + "}\n"
818
819         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"
820         for var in flattened_field_var_conversions:
821             if isinstance(var, ConvInfo):
822                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
823             else:
824                 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
825         out_c = out_c + ") {\n"
826         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
827         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
828         for var in flattened_field_var_conversions:
829             if isinstance(var, ConvInfo):
830                 out_c = out_c + ", " + var.arg_name
831             else:
832                 out_c = out_c + ", " + var[1]
833         out_c = out_c + ");\n"
834         out_c = out_c + "\treturn (long)res_ptr;\n"
835         out_c = out_c + "}\n"
836
837         return (out_typescript_bindings, out_typescript_human, out_c)
838
839     def trait_struct_inc_refcnt(self, ty_info):
840         return ""
841
842     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
843         java_hu_type = struct_name.replace("LDK", "")
844
845         out_java_enum = ""
846         out_java = ""
847         out_c = ""
848
849         out_java_enum += (self.hu_struct_file_prefix)
850         out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
851         out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
852         out_java_enum += ("\tprotected finalize() {\n")
853         out_java_enum += ("\t\tsuper.finalize();\n")
854         out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
855         out_java_enum += ("\t}\n")
856         out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
857         out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
858         java_hu_subclasses = ""
859
860         out_java +=  ("\tpublic static class " + struct_name + " {\n")
861         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
862         for var in variant_list:
863             out_java +=  ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
864             java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
865             out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
866             out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
867             init_meth_params = ""
868             init_meth_body = ""
869             hu_conv_body = ""
870             for idx, (field_ty, field_docs) in enumerate(var.fields):
871                 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
872                 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
873                 if field_ty.to_hu_conv is not None:
874                     hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
875                     hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
876                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
877                 else:
878                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
879                 if idx > 0:
880                     init_meth_params = init_meth_params + ", "
881                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
882                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
883             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
884             out_java +=  (init_meth_body)
885             out_java +=  ("}\n")
886             out_java += ("\t\t}\n")
887             out_java_enum += ("\t\t}\n")
888             java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
889             java_hu_subclasses = java_hu_subclasses + hu_conv_body
890             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
891         out_java += ("\t\tstatic native void init();\n")
892         out_java += ("\t}\n")
893         out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
894         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
895         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
896
897         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")
898         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
899         out_c += ("\tswitch(obj->tag) {\n")
900         for var in variant_list:
901             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
902             c_params = []
903             for idx, (field_map, _) in enumerate(var.fields):
904                 if field_map.ret_conv is not None:
905                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
906                     if var.tuple_variant:
907                         out_c += "obj->" + camel_to_snake(var.var_name)
908                     else:
909                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
910                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
911                     c_params.append(field_map.ret_conv_name)
912                 else:
913                     if var.tuple_variant:
914                         c_params.append("obj->" + camel_to_snake(var.var_name))
915                     else:
916                         c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
917             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
918             out_c += ("\t\t}\n")
919         out_c += ("\t\tdefault: abort();\n")
920         out_c += ("\t}\n}\n")
921         out_java_enum += ("}\n")
922         out_java_enum += (java_hu_subclasses)
923         return (out_java, out_java_enum, out_c)
924
925     def map_opaque_struct(self, struct_name, struct_doc_comment):
926         implementations = ""
927         method_header = ""
928         if struct_name.startswith("LDKLocked"):
929             implementations += "implements AutoCloseable "
930             method_header = """
931                 public close() {
932 """
933         else:
934             method_header = """
935                 protected finalize() {
936                     super.finalize();
937 """
938
939         out_opaque_struct_human = f"""
940             {self.hu_struct_file_prefix}
941
942             export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
943                 constructor(_dummy: object, ptr: number) {{
944                     super(ptr);
945                 }}
946
947                 {method_header}
948                     if (this.ptr != 0) {{
949                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
950                     }}
951                 }}
952 """
953         return out_opaque_struct_human
954
955     def map_tuple(self, struct_name):
956         return self.map_opaque_struct(struct_name, "A Tuple")
957
958     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):
959         out_java = ""
960         out_c = ""
961         out_java_struct = None
962
963         out_java += ("\tpublic static native ")
964         out_c += (self.c_fn_ty_pfx)
965         out_c += (return_type_info.c_ty)
966         out_java += (return_type_info.java_ty)
967         if return_type_info.ret_conv is not None:
968             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
969         out_java += (" " + method_name + "(")
970         out_c += (" "  + self.c_fn_name_define_pfx(method_name, True))
971
972         method_argument_string = ""
973         native_call_argument_string = ""
974         for idx, arg_conv_info in enumerate(argument_types):
975             if idx != 0:
976                 method_argument_string += (", ")
977                 native_call_argument_string += ', '
978                 out_c += (", ")
979             if arg_conv_info.c_ty != "void":
980                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
981                 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
982                 native_argument = arg_conv_info.arg_name
983                 if needs_encoding:
984                     converter = self.wasm_encoding_map[arg_conv_info.c_ty]
985                     native_argument = f"{converter}({arg_conv_info.arg_name})"
986                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
987                 native_call_argument_string += native_argument
988
989         has_return_value = return_type_info.c_ty != 'void'
990         needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
991         return_statement = 'return nativeResponseValue;'
992         if not has_return_value:
993             return_statement = '// debug statements here'
994         elif needs_decoding:
995             converter = self.wasm_decoding_map[return_type_info.c_ty]
996             return_statement = f"return {converter}(nativeResponseValue);"
997
998         out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
999                 if(!isWasmInitialized) {{
1000                         throw new Error("initializeWasm() must be awaited first!");
1001                 }}
1002                 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
1003                 {return_statement}
1004         }}
1005 """
1006
1007         out_java_struct = ""
1008         if not args_known:
1009             out_java_struct += ("\t// Skipped " + method_name + "\n")
1010         else:
1011             if not takes_self:
1012                 out_java_struct += (
1013                         "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
1014             else:
1015                 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
1016             for idx, arg in enumerate(argument_types):
1017                 if idx != 0:
1018                     if not takes_self or idx > 1:
1019                         out_java_struct += (", ")
1020                 elif takes_self:
1021                     continue
1022                 if arg.java_ty != "void":
1023                     if arg.arg_name in default_constructor_args:
1024                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1025                             if explode_idx != 0:
1026                                 out_java_struct += (", ")
1027                             out_java_struct += (
1028                                     explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1029                     else:
1030                         out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
1031
1032         out_c += (") {\n")
1033         if out_java_struct is not None:
1034             out_java_struct += (") {\n")
1035         for info in argument_types:
1036             if info.arg_conv is not None:
1037                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1038         if return_type_info.ret_conv is not None:
1039             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1040         elif return_type_info.c_ty != "void":
1041             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1042         else:
1043             out_c += ("\t")
1044         if c_call_string is None:
1045             out_c += (method_name + "(")
1046         else:
1047             out_c += (c_call_string)
1048         for idx, info in enumerate(argument_types):
1049             if info.arg_conv_name is not None:
1050                 if idx != 0:
1051                     out_c += (", ")
1052                 elif c_call_string is not None:
1053                     continue
1054                 out_c += (info.arg_conv_name)
1055         out_c += (")")
1056         if return_type_info.ret_conv is not None:
1057             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1058         else:
1059             out_c += (";")
1060         for info in argument_types:
1061             if info.arg_conv_cleanup is not None:
1062                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1063         if return_type_info.ret_conv is not None:
1064             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1065         elif return_type_info.c_ty != "void":
1066             out_c += ("\n\treturn ret_val;")
1067         out_c += ("\n}\n\n")
1068
1069         if args_known:
1070             out_java_struct += ("\t\t")
1071             if return_type_info.java_ty != "void":
1072                 out_java_struct += (return_type_info.java_ty + " ret = ")
1073             out_java_struct += ("bindings." + method_name + "(")
1074             for idx, info in enumerate(argument_types):
1075                 if idx != 0:
1076                     out_java_struct += (", ")
1077                 if idx == 0 and takes_self:
1078                     out_java_struct += ("this.ptr")
1079                 elif info.arg_name in default_constructor_args:
1080                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1081                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1082                         if explode_idx != 0:
1083                             out_java_struct += (", ")
1084                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1085                         if explode_arg.from_hu_conv is not None:
1086                             out_java_struct += (
1087                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1088                         else:
1089                             out_java_struct += (expl_arg_name)
1090                     out_java_struct += (")")
1091                 elif info.from_hu_conv is not None:
1092                     out_java_struct += (info.from_hu_conv[0])
1093                 else:
1094                     out_java_struct += (info.arg_name)
1095             out_java_struct += (");\n")
1096             if return_type_info.to_hu_conv is not None:
1097                 if not takes_self:
1098                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1099                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1100                 else:
1101                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1102
1103             for idx, info in enumerate(argument_types):
1104                 if idx == 0 and takes_self:
1105                     pass
1106                 elif info.arg_name in default_constructor_args:
1107                     for explode_arg in default_constructor_args[info.arg_name]:
1108                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1109                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1110                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1111                                                                                              expl_arg_name).replace(
1112                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1113                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1114                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1115                         out_java_struct += (
1116                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1117                     else:
1118                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1119
1120             if return_type_info.to_hu_conv_name is not None:
1121                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1122             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1123                 out_java_struct += ("\t\treturn ret;\n")
1124             out_java_struct += ("\t}\n\n")
1125
1126         return (out_java, out_c, out_java_struct)