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