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