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